1 回答
TA贡献1874条经验 获得超12个赞
如果您愿意将 product_id 作为密钥,那么您可以这样做:
$a = [
0 => [
"product_id" => "a",
"quantity_1" => "1"
],
1 => [
"product_id" => "b",
"quantity_1" => "2"
],
2 => [
"product_id" => "c",
"quantity_1" => "1"
]
];
$b = [
0 => [
"product_id" => "a",
"quantity_2" => "1"
],
1 => [
"product_id" => "d",
"quantity_2" => "2"
]
];
print_r(
array_replace_recursive(
array_column($a, null, 'product_id'),
array_column($b, null, 'product_id')
)
);
输出
Array
(
[a] => Array
(
[product_id] => a
[quantity_1] => 1
[quantity_2] => 1
)
[b] => Array
(
[product_id] => b
[quantity_1] => 2
)
[c] => Array
(
[product_id] => c
[quantity_1] => 1
)
[d] => Array
(
[product_id] => d
[quantity_2] => 2
)
)
沙盒
您可以随时从结果中删除密钥,array_values如下所示:
print_r(
array_values(
array_replace_recursive(
array_column($a, null, 'product_id'),
array_column($b, null, 'product_id')
)
)
);
-注意- product_ids 在每个数组中必须是唯一的,这样才能工作。否则,您可以简单地使用 foreach 循环来完成。
$c = [];
foreach(array_merge($a,$b) as $v){
$k = $v['product_id'];
if(!isset($c[$k])){
$c[$k] = $v;
}else{
$c[$k] = array_merge($c[$k],$v);
}
}
print_r($c);
沙盒
我会发布输出,但它是相同的:) - 这就是重点。此外,我更喜欢尽可能少地引用这些键。它可以使维护代码更容易一些。
- 1 回答
- 0 关注
- 163 浏览
添加回答
举报