根据PHP中的匹配列值合并数组

问题描述:

我想基于列的匹配值合并两个数组.这是我的2个数组.

I want to merge two arrays base on match value of column. Here is my 2 arrays.

$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"
   }
}

我想用这两个数组得到的东西是这样的.

what i wanna get with this two arrays is something like this.

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']和相同的值.

as you can see two array has the same key ['category_id'] and same value as well.

所以我要完成的结果是,将['total_process_per_category']和['total_pinned_per_category']放置在基于['category_id']的同一数组上.

so what i want to accomplish is make a result that ['total_process_per_category'] and ['total_pinned_per_category'] are place together on the same array base on their ['category_id'].

我使用嵌套的foreach得到了这个.但是对于我来说,它看起来太丑陋了.有什么建议吗?

I got this using nested foreach. but it looks so ugly code for me. so any suggestions?

您可以尝试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);