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.