[英]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:我有一个关联数组 $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:我想将此数组转换为关联数组,其中“依赖”作为关联数组,具有两个字段
dep_name
和dep_id
字段,如下所示:
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.我能够使用具有各自值的键
emp_id
、 emp_name
和emp_email
创建关联数组,但无法将dep_id
和dep_name
推入“依赖”字段。
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也可能您需要重新索引数组,因为索引将是新 arr 中的 emp_id
Note: i haven't tested code.注意:我还没有测试代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.