按共享列值合并关联数组的数组



我想根据一个公共列值合并两个数组。这是我的 2 个数组:

$array1 = [
    [
        "total_process_per_category" => "6",
        "category_id" => "1"
    ],
    [
        "total_process_per_category" => "2",
        "category_id" => "2"
    ]
];
$array2 = [
    [
        "total_pinned_per_category" => "16",
        "category_id" => "1"
    ],
    [
        "total_pinned_per_category" => "4",
        "category_id" => "2"
    ]
];

我想合并这些数组以获得:

array (
  0 => 
  array (
    'total_process_per_category' => '6',
    'total_pinned_per_category' => '16',
    'category_id' => '1',
  ),
  1 => 
  array (
    'total_process_per_category' => '2',
    'total_pinned_per_category' => '4',
    'category_id' => '2',
  ),
)

如您所见,这两个数组具有相同的键 ['category_id'] 和相同的值。

我想根据它们的 ['category_id'] 值将 ['total_process_per_category] 和 ['total_pinned_per_category'] 放在同一个数组上。

我用嵌套的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);

这可以在没有"丑陋的嵌套foreach"的情况下完成。在迭代之前合并两个数组,按category_id值分组。 循环后,用 array_values() 清除临时的第一级键。

代码: (演示) (array_reduce() 版本)

$result = [];
foreach (array_merge($array1, $array2) as $row) {
    $result[$row['category_id']] = ($result[$row['category_id']] ?? []) + $row;
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'total_process_per_category' => '6',
    'category_id' => '1',
    'total_pinned_per_category' => '16',
  ),
  1 => 
  array (
    'total_process_per_category' => '2',
    'category_id' => '2',
    'total_pinned_per_category' => '4',
  ),
)

你想要这样的东西吗:

foreach ( $array1 as $index => $value ) {
    $mergeArray[] = [ $value, $array2[$index]];
}

最新更新