简体   繁体   中英

Convert an associative array into an associative array which has a key with another associative array as its value in php

I have an associative array $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
  )
)

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
    ]
  )
)

I tried using this way:

$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"];                         
       ];                       
 }

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.

Try this

$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']
    ];
}

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

Note: i haven't tested code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM