通过共享的列值合并关联数组的数组

5

我希望根据一个共同的列值合并两个数组。这是我的两个数组:

$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'],并且相同的值。

我想要创建一个结果,其中['total_process_per_category']和['total_pinned_per_category']基于它们的['category_id']值放在同一个数组中。

我使用了一种嵌套的foreach方法来实现,但是它看起来很不美观。请给我展示一种更好的方法。

3个回答

6
你可以尝试使用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

这可以在没有“丑陋的嵌套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',
  ),
)

-1
你想要类似这样的东西吗:
foreach ( $array1 as $index => $value ) {
    $mergeArray[] = [ $value, $array2[$index]];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接