根据PHP中的匹配列值合并数组 [英] Merge array according to match column values in PHP

查看:153
本文介绍了根据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);

这篇关于根据PHP中的匹配列值合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆