且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并两个多维数组

更新时间:2022-12-09 19:09:23

您要执行的操作是将多维数组按特定对象分组列,然后将其合并。

What you want to do is grouping an multi dimensional array by a specific column and then merge it.

可以使用 array_reduce 进行分组,方法是创建一个新的关联数组,

The grouping can be done with array_reduce, by creating a new associative array, that uses the categories as keys.

$groupedProducts = array_reduce($products, function($carry, $product){
    if (!array_key_exists($product['codename'], $carry)) {
        $carry[$product['codename']] = [];
    }
    $carry[$product['codename']][] = $product;
    return $carry;
}, []);

这将创建以下数据结构:

This will create the following data structure:

$groupedProducts = [
    'fruit' => [
        [
            'codename' => 'fruit',
            'name' => 'banana',
            ... some other stuff ...
        ],
        [
            'codename' => 'fruit',
            'name' => 'apple',
            ... some other stuff ...
        ]
    ],
    'vegetables' => [
        [
            'codename' => 'vegetables',
            'name' => 'cauliflower',
            ... some other stuff ...
        ]
    ],
    'cars' => [
        [
            'codename' => 'cars',
            'name' => 'audi',
            ... some other stuff ...
        ],
        [
            'codename' => 'cars',
            'name' => 'volvo',
            ... some other stuff ...
        ]
    ],
]

如您所见,所有产品均按代号分组。如果您不希望内部数组中的代号键,则可以在 array_reduce 匿名函数中取消设置或使用 array_intersect_key 在其中选择要保留的特定密钥。

As you can see all products are grouped by the codename. If you do not want the codename key in the inner arrays you can unset it in the array_reduce anonymous function, or use array_intersect_key in there to select specific keys you want to keep.

如果您不做任何调整,就可以重复使用代码。还要按类别对最终数组进行分组。

You can reuse the code with little adjustments if you want to group the final array by categories as well.

接下来是合并。在这里,您可以在初始数组上使用 array_map 向其中添加排序:

Next comes the merge. Here you can use array_map on the initial array to add the sorts to it:

$finalArray = array_map(function($type) use ($groupedProducts) {
    if (array_key_exists($type['unique_codename'], $groupedProducts)) {
       $type['sorts'] = $groupedProducts[$type['unique_codename']];
    }
    return $type;
}, $types);

此代码将创建您要构建的最终数组。

This code will create the final array you wanted to build.