根据键值合并数组 [英] Merging arrays based on a value of the key

查看:111
本文介绍了根据键值合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有id键的数组,我想根据该数组的键和键值将数据合并在一起.数据如下所示:

I have two arrays of arrays that have an id key, and I'd like to merge the data together based on that array's key and key value. The data would look something like:

    $color = [
        ['id' => 1, 'color' => 'red'],
        ['id' => 2, 'color' => 'green'],
        ['id' => 3, 'color' => 'blue'],
    ];

    $size = [
        ['id' => 1, 'size' => 'SM'],
        ['id' => 2, 'size' => 'XL'],
        ['id' => 3, 'size' => 'MD'],
        ['id' => 4, 'size' => 'LG'],
    ];

    $combined = [
        ['id' => 1, 'color' => 'red', 'size' => 'SM'],
        ['id' => 2, 'color' => 'green', 'size' => 'XL'],
        ['id' => 3, 'color' => 'blue', 'size' => 'MD'],
        ['id' => 4, 'size' => 'LG'],
    ];

是否存在处理此类问题的特别有效的功能或技巧?还是我应该循环遍历一个数组的元素,然后将内容推到另一个数组?

Is there a particularly efficient function or trick for handling something like this? Or should I just loop through the elements of one array and push the contents to the other?

我也在使用Laravel,数据是一个雄辩的查询的结果,因此,如果可以使代码更简洁,我也可以利用这些集合.

I'm also using Laravel, and the data is a result of an eloquent query, so I can also utilize the collections if it would make the code cleaner.

推荐答案

在特定情况下,您可以使用array_replace_recursive合并数组.

You can use array_replace_recursive to merge the arrays in your particular situation.

$color = array(
    array('id' => 1, 'color' => 'red'),
    array('id' => 2, 'color' => 'green'),
    array('id' => 3, 'color' => 'blue'),
);

$size = array(
    array('id' => 1, 'size' => 'SM'),
    array('id' => 2, 'size' => 'XL'),
    array('id' => 3, 'size' => 'MD'),
    array('id' => 4, 'size' => 'LG'),
);

$merged = array_replace_recursive($color, $size);

输出:

array(4) {
  [0]=>
  array(3) {
    ["id"]=>
    int(1)
    ["color"]=>
    string(3) "red"
    ["size"]=>
    string(2) "SM"
  }
  [1]=>
  array(3) {
    ["id"]=>
    int(2)
    ["color"]=>
    string(5) "green"
    ["size"]=>
    string(2) "XL"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(3)
    ["color"]=>
    string(4) "blue"
    ["size"]=>
    string(2) "MD"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(4)
    ["size"]=>
    string(2) "LG"
  }
}

注意:我使用传统的数组布局,因为我的PHP版本尚不支持新的数组布局:)

Note: I used the traditional array layout because my PHP version won't support the new one yet :)

您也可以使用array_map.这样一来,您就可以通过少量调整添加任意数量的数组.

You can also use array_map. This will let you add as much arrays as you want with a little tweaking.

$merged = array_map(function ($c, $s) {
    return array_merge($c, $s);
}, $color, $size);

var_dump($merged); // See output above

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

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