根据键值合并数组 [英] Merging arrays based on a value of the key
问题描述
我有两个数组,它们有一个 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,数据是 eloquent 查询的结果,所以如果可以使代码更简洁,我也可以使用集合.
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屋!