中找到你的结果
我有这个数组,我想知道我怎么能:
- 总数量,所以最后我只收到唯一的产品id及其数量,例如:
产品805 - 1件
产品编号1118 - 2+3+4 = 9件
array(2){
["product"]=> array(4){
[0]=> string(3) "805"
[1]=> string(4) "1118"
[2]=> string(4) "1118"
[3]=> string(4) "1118"
}
["qty"]=> array(4) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(1) "3"
[3]=> string(1) "4"
}
}
提前感谢,
$productQuantities = array();
$products = array("805","1118","1118","1118");
$quantities = array(1,2,3,4);
foreach($products AS $key=>$productId){
$quantity = (int) $quantities[$key];
if(isset($productQuantities[$productId])){
$productQuantities[$productId] += $quantity;
} else {
$productQuantities[$productId] = $quantity;
}
}
var_dump($productQuantities);
你可以试试:
$zipped=array_map(
null,
$your_array['product'],
$your_array['qty']
);
$compact = array();
foreach ($zipped as $k => $v){
if(!array_key_exists($v[0], $compact)){
$compact[$v[0]] = $v[1];
} else {
$compact[$v[0]] += $v[1];
}
}
你会在$compact