将关联数组转换为关联数组,该关联数组具有一个键,该键中的另一个关联数组作为键在php中的值

将关联数组转换为关联数组,该关联数组具有一个键,该键中的另一个关联数组作为键在php中的值

问题描述:

我有一个关联数组$ data:

Array
(
  [0] => Array
  (
    [emp_id] => 1
    [emp_name] => Emp1
    [emp_email] => emp1@example.com
    [dep_id] => 1
    [dep_name] => Mario
  )
  [1] => Array
  (
    [emp_id] => 1
    [emp_name] => Emp1
    [emp_email] => emp1@example.com
    [dep_id] => 2
    [dep_name] => Tony
  )
  [2] => Array
  (
    [emp_id] => 2
    [emp_name] => Emp2
    [emp_email] => emp2@example.com
    [dep_id] => 3
    [dep_name] => Jack
  )
)

我想将此数组转换为具有'depend'作为关联数组的关联数组,该关联数组具有两个字段 dep_name dep_id 字段,如下所示:

I want to convert this array into an associative array with the 'dependent' as an associative array with two fields dep_name and dep_id field like this:

Array
(
  [0] => Array
  (
    [emp_id] => 1
    [emp_name] => Emp1
    [emp_email] => emp1@example.com
    [dependant] => [
      [
        [dep_id] => 1
        [dep_name] => Mario
      ]
      [
        [dep_id] => 2
        [dep_name] => Tony
      ]
    ]
)
[1] => Array
(
  [emp_id] => 2
  [emp_name] => Emp2
  [emp_email] => emp2@example.com
  [dependant] => [
    [
        [dep_id] => 3
        [dep_name] => Jack
    ]
  )
)

我尝试过这种方式:

$newEmployeeInfo = [];
$newEmployeeKey = [];
$newDependantInfo = [];
$newKey = 0;
foreach($data as $dataKey => $dataValue){
   if(!in_array($dataValue["emp_id"],$newEmployeeKey)){
       ++$newKey;
       $newEmployeeInfo[$newKey]["emp_id"] = $dataValue["emp_id"];
       $newEmployeeInfo[$newKey]["emp_name"] = $dataValue["emp_name"];
       $newEmployeeInfo[$newKey]["emp_email"] = $dataValue["emp_email"];
   }                
   $newEmployeeInfo[$newKey]["dependant"][$dataKey] = $dataValue[$newDependantInfo];       
       $newDependantInfo[$newKey]["dep_id"] = $dataValue["dep_id"];
       $newDependantInfo[$newKey]["dep_name"] = $dataValue["dep_name"];                         
       ];                       
 }

我能够分别使用键 emp_id emp_name emp_email 创建具有相应值的关联数组,但是无法推送将 dep_id dep_name 转换为从属"字段.

I was able to create the associative array with the keys emp_id, emp_name and emp_email with the respective values, but was unable to push dep_id and dep_name into the "dependant" field.

尝试一下

$newArr = [];
foreach($data as $key => $value){
   $newArr[$value['emp_id']]['emp_id'] = $value['emp_id'];
   $newArr[$value['emp_id']]['emp_name'] = $value['emp_name'];
   $newArr[$value['emp_id']]['emp_email'] = $value['emp_email'];
   $newArr[$value['emp_id']]['dependant'][] = [
       'dep_id'=>$value['dep_id'],
       'dep_name'=>$value['dep_name']
    ];
}

还可能需要重新索引数组,因为索引将在新arr中为emp_id

also maybe you need to reindex the array as index will be emp_id in new arr

注意:我尚未测试代码.

Note: i haven't tested code.