如何基于PHP中的价值及其关键合并数组?
问题描述:
我有一个数组看起来像this.I希望通过他们的订单ID合并数组。搜索结果
阵列(
I have an array looks like this.I want to merge array by their order id.
Array(
[0] => Array
(
[orderId] => 152
[prodName] => Red Dri-fit Undershirt
[quantity] => 2
[cartId] => 677
)
[1] => Array
(
[orderId] => 151
[prodName] => Practice Shorts
[quantity] => 2
[cartId] => 667
)
[2] => Array
(
[orderId] => 151
[prodName] => Red Dri-fit Undershirt
[quantity] => 2
[cartId] => 668
)
)搜索结果
它应该是这个样子。搜索结果
排列
(
)
It should look something like this.
Array
(
[152] => Array
(
[prodName] => Red Dri-fit Undershirt
[quantity] => 2
[cartId] => 677
)
[151] => Array
(
[1] => Array
(
[prodName] => Practice Shorts
[quantity] => 2
[cartId] => 667
)
[2] => Array
(
[prodName] => Red Dri-fit Undershirt
[quantity] => 2
[cartId] => 668
)
)
)
我被他们的订单ID试图其中两个两个数组。
我找了一个功能,如果有的话,preserve或合并值转换成类似的密钥,但至今没有运气。
I am trying two these two arrays by their order ids. I am looking for a function, if any, to preserve or merge values into similar key, but no luck so far.
答
我觉得这是更直截了当。
I think this is much more straight forward.
$collections = array();
foreach($products as $product){
if(!empty($collections[$product['orderId']]) || !isset($collections[$product['orderId']])){
array_push($collections[$product['orderId']],
array(
'prodName' => $product['prodName'],
'quantity' => $product['quantity'],
'cartId' => $product['cartId'],
'isPack' => $product['isPack']
)
);
}else{
$collections[$product['orderId']] = array(
array(
'prodName' => $product['prodName'],
'quantity' => $product['quantity'],
'cartId' => $product['cartId'],
'isPack' => $product['isPack']
)
);
}
}
echo '<pre>';
print_r($collections);