我想从$ employee_salary数组中的$ employee数组中添加薪水键

我想从$ employee_salary数组中的$ employee数组中添加薪水关键字,这两个数组都是关联的,并且salary仅根据索引添加到薪水。存在一些未定义偏移量的错误。我无法识别问题。这些错误就像未定义的偏移量一样,这会是什么问题?


    $employee = array

(

0=>

    array("employee_id"=>1, "firstName"=>"Zahir", "lastName"=>"Alam", "Age"=>25, "Company"=>"Switchme", "Role"=>"Developer", "Department"=>"Tech"

        ,"Head"=>

            array("Id"=>3 , "Name"=>"Sourasis Roy")

    )

,

1=>

    array("employee_id"=>2, "firstName"=>"Amith", "lastName"=>"Manniken", "Age"=>25, "Company"=>"Switchme", "Role"=>"Developer", "Department"=>"Tech"

        ,"Head"=>

            array("Id"=>3 , "Name"=>"Sourasis Roy")

    )

,

2=>

    array("employee_id"=>3, "firstName"=>"Sourasis", "lastName"=>"Roy", "Age"=>28, "Company"=>"Switchme", "Role"=>"CTO")

,

3=>

    array("employee_id"=>4, "firstName"=>"Aditya", "lastName"=>"Mishra", "Age"=>29, "Company"=>"Switchme", "Department"=>"Tech", "Role"=>"CEO")

,

4=>

    array("employee_id"=>5, "firstName"=>"Priti", "lastName"=>"Lata", "Age"=>24, "Company"=>"Switchme", "Role"=>"HR")

,

5=>

    array("employee_id"=>6, "firstName"=>"Sumita", "lastName"=>"Nath", "Age"=>24, "Company"=>"Switchme", "Role"=>"HLA Head", "Department"=>"Crm")

,

6=>

    array("employee_id"=>7, "firstName"=>"Tarini", "lastName"=>"Khanna", "Age"=>22, "Company"=>"Switchme", "Role"=>"Content Writer")

,

7=>

    array("employee_id"=>8, "firstName"=>"Abhisek", "lastName"=>"Soni", "Age"=>23, "Company"=>"Switchme", "Role"=>"HLA", "Department"=>"Crm","Head"=>array("Id"=>5 , "Name"=>"Sumita Nath")

    )

,

8=>

    array("employee_id"=>9, "firstName"=>"Ankit", "lastName"=>"Pump", "Age"=>23, "Company"=>"Switchme", "Role"=>"HLA", "Department"=>"Crm"

        ,"Head"=>

            array("Id"=>5 , "Name"=>"Sumita Nath")

    )

,

9=>

    array("employee_id"=>10, "firstName"=>"Pogo", "lastName"=>"Laal", "Age"=>23, "Company"=>"Switchme", "Role"=>"Designer")

,

10=>

    array("employee_id"=>11, "firstName"=>"Sabina", "lastName"=>"Sekh", "Age"=>28, "Company"=>"Switchme", "Role"=>"HLA Head", "Department"=>"Crm")

,

不负相思意
浏览 136回答 3
3回答

白板的微信

如果您可以注意到,两者$employee[$j]和$employee_salary[$j]都是数组,那么您不应该等同于它们之间的比较。另外,$employee和$employee_salary数组的大小都不相同,这就是为什么在循环中遇到未定义的索引错误的原因。$employee_salary[$j]for将嵌套foreach循环与引用一起使用以实现所需的结果,如下所示:foreach($employee as &$emp1){    foreach($employee_salary as $emp2){        if($emp1['employee_id'] == $emp2['employee_id']){            $emp1['salary'] = $emp2['salary'];        }    }}// Display complete array structure of $employeevar_dump($employee);

杨魅力

您可以简单地使用 array_walk$emp_s = array_column($employee_salary, 'salary','employee_id');array_walk($employee, function(&$v, $k) use ($emp_s){  if(array_key_exists($k, $emp_s)){    $v['salary'] = $emp_s[$k];  }});或者$temp        = array_column($employee_salary, 'salary','employee_id');array_walk($employee, function(&$v, $k) use ($temp){    $v['salary'] = array_key_exists($k, $temp) ? $temp[$k] : null;});
打开App,查看更多内容
随时随地看视频慕课网APP