I have a purchase table in a mall. There are orders in the purchase table. Some orders have the same products as other orders. Then the amount field inside is the purchase quantity of the product in the order. I want to determine if this order is the same as the purchase quantity of the product in the order. If the ID of a certain product is the same, the quantity in the amount field will be superimposed. What should I do?
array(
[0]=>
'pid'=>7,
'amount'=>1,
[1]=>
'pid'=>7,
'amount'=>2,
[2]=>
'pid'=>8,
'amount'=>1,
)
For example, in this array, there are two pid values that are the same. I will add the combined values to form this array
array(
[0]=>
'pid'=>7,
'amount'=>3,
[1]=>
'pid'=>8,
'amount'=>1,
)
伊谢尔伦2017-05-16 13:03:33
Use pid as the key of the new array
$returnarr = array();
foreach($data as $val) {
if(isset($returnarr[$val['pid']])) {
$returnarr[$val['pid']]['amount'] += $val['amount'];
} else {
$returnarr[$val['pid']]['pid'] = $val['pid'];
$returnarr[$val['pid']]['amount'] = $val['amount'];
}
}
怪我咯2017-05-16 13:03:33
Write a loop, judge whether there are the same ones based on pid, merge them, and finally generate a new array OK
phpcn_u15822017-05-16 13:03:33
$allok = array();
foreach ($all as $key1 => &$value1){
foreach ($value1 as $key2 => $value2){
$allok[$value2['pid']] = $value2;
$allok[$value2['pid']] = $allok[$value2['pid']]['amount'] + $value2['amount'];
/*$queryproductshop = Model('Product')->queryidshop($value2['pid']);
$queryshopclass = Model('ProductClassify')->SaleConfigShopClass($queryproductshop['cid']);
$queryproductshop['class'] = $queryshopclass['title'];
$allshop[] = $queryproductshop;*/
}
}
dump($allok);
I have solved it myself, it is too complicated to think about it
我想大声告诉你2017-05-16 13:03:33
//The code is as follows, I hope it will be helpful to you.
$orderInfo = array(
[0]=>
'pid'=>7,
'amount'=>1,
[1]=>
'pid'=>7,
'amount'=>2,
[2]=>
'pid'=>8,
'amount'=>1,
);
foreach ($orderInfo as $k=>$v)
{
$bKey=$v['pid'];
if(!array_key_exists($bKey, $orderArr))
{
$orderArr[$bKey] = [];
$sumData[$bKey] = 0;
}
$orderArr[$bKey]=$v;
$sumData[$bKey]+=$orderArr[$bKey]['amount'];
$orderArr[$bKey]['amount']=$sumData[$bKey];
}
var_dump($orderArr);