我想根据列的匹配值合并两个数组。这是我的 2 个数组。
$array1 = array(2) {
[0] => array(2) {
["total_process_per_category"] => string(2) "6"
["category_id"] => string(1) "1"
}
[1] => array(2) {
["total_process_per_category"] => string(1) "2"
["category_id"] => string(1) "2"
}
}
$array2 = array(2) {
[0] => array(2) {
["total_pinned_per_category"] => string(2) "16"
["category_id"] => string(1) "1"
}
[1] => array(2) {
["total_pinned_per_category"] => string(1) "4"
["category_id"] => string(1) "2"
}
}
Run Code Online (Sandbox Code Playgroud)
我想用这两个数组得到的东西是这样的。
array(2) {
[0] => array(3) {
["total_process_per_category"] => string(2) "6"
["total_pinned_per_category"] => string(2) "16"
["category_id"] => string(1) "1"
}
[1] => array(3) {
["total_process_per_category"] => string(2) "2"
["total_pinned_per_category"] => string(1) "4"
["category_id"] => string(1) "2"
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,两个数组具有相同的键 ['category_id'] 和相同的值。
所以我想要完成的是使 ['total_process_per_category'] 和 ['total_pinned_per_category'] 基于它们的 ['category_id'] 放在同一个数组上。
我使用嵌套的 foreach 得到了这个。但对我来说它看起来很丑陋的代码。所以有什么建议吗?
你可以试试array_reduce:
$someVariable = 'someValue';
$result = array_reduce(array_merge($array1, $array2), function ($carry, $item) use ($someVariable) {
if (isset($carry[$item['category_id']])) {
$carry[$item['category_id']] = array_merge($carry[$item['category_id']], $item);
} else {
$carry[$item['category_id']] = $item;
}
return $carry;
}, array());
var_dump($result);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1966 次 |
| 最近记录: |