有条件地组合2个PHP数组的干净方法吗? 我分别从两个数组中得到以下JSON-Response:
第一阵列:
[
{
"field": {
"id": 20,
"name": "Erfolge",
"field-id": "erfolge",
"type": "textarea"
}
},
{
"field": {
"id": 29,
"name": "Sprachen",
"field-id": "sprachen",
"type": "text"
}
}
]
第二阵列:
[
{
"field": {
"id": 20,
"name": "Erfolge",
"field-id": "erfolge",
"type": "textarea"
},
"value": "new entry"
},
{
"field": {
"id": 4,
"name": "Trikotnummer",
"field-id": "trikotnummer",
"type": "number"
},
"value": "test"
},
{
"field": {
"id": 29,
"name": "Sprachen",
"field-id": "sprachen",
"type": "text"
},
"value": "Text"
}
]
我想要以下目标输出:
[
{
"field": {
"id": 20,
"name": "Erfolge",
"field-id": "erfolge",
"type": "textarea"
},
value: "new entry"
},
{
"field": {
"id": 29,
"name": "Sprachen",
"field-id": "sprachen",
"type": "text"
},
value: "Text"
}
]
这意味着如果第一个数组中存在该字段,则必须仅添加值。 我当前的解决方案为我提供了没有正确映射的所有字段:
$fieldData = array();
foreach ($fields as $field) {
$fieldData[]['fields'] = $field->getArrayCopy();
}
// Get Values
$values = $user->getProfileFieldValue();
$fieldValue = array();
foreach ($values as $value) {
$fieldValue[] = $value->getArrayCopy();
}
$result = array_merge($fieldData, $fieldValue);
我应该使用函数array_walk吗?
答案 0 :(得分:4)
这是一种昂贵的方法,它会搜索第二个数组,寻找与第一个数组中的ID匹配的元素。
$result = array();
foreach ($first as $e1) {
$id = $e1['field']['id'];
foreach ($secondArray as $e2) {
if ($e2['field']['id'] == $id) {
$e1['value'] = $e2['value'];
break;
}
}
$result[] = $e1;
}
如果第二个数组非常大,您可以通过首先创建一个关联数组来优化它,该关键数组的键是第二个数组中的ID,值是值。
答案 1 :(得分:2)
https://secure.php.net/manual/en/function.array-uintersect.php
$res = array_uintersect($arr1, $arr2, function($a, $b){
return $a['field']['id'] - $b['field']['id'];
});