php数组根据值合并,php – 根据键的值合并数组

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

$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版本不支持新版本:)

第二种选择

您也可以使用array_map.这将允许您通过一些调整添加尽可能多的数组.

$merged = array_map(function ($c, $s) {

return array_merge($c, $s);

}, $color, $size);

var_dump($merged); // See output above

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值