我想根据列的匹配值合并两个数组。这是我的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"
}
}
我想用这两个阵列获得的是这样的。
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"
}
}
你可以看到两个数组具有相同的键[' category_id']并且具有相同的值。
所以我想要完成的是将[' total_process_per_category']和[' total_pinned_per_category']放在他们[' CATEGORY_ID'。]
我使用嵌套的foreach得到了这个。但它对我来说看起来很难看。那么有什么建议吗?
答案 0 :(得分:3)
您可以尝试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);
答案 1 :(得分:0)
您想要类似的东西吗?
foreach ( $array1 as $index => $value ) {
$mergeArray[] = [ $value, $array2[$index]];
}