Heim > Fragen und Antworten > Hauptteil
我做一个商城里面有个采购表,采购表里面有订单,有些订单和另一些订单的商品是一样的,然后里面字段amount是订单这个商品的购买数量,我想判断如果这个订单和某个商品id是一样就叠加amount字段的数量,该怎么做?
array(
[0]=>
'pid'=>7,
'amount'=>1,
[1]=>
'pid'=>7,
'amount'=>2,
[2]=>
'pid'=>8,
'amount'=>1,
)
比如这数组,有2个pid值是一样的,我就把他结合数值相加变成这一下数组
array(
[0]=>
'pid'=>7,
'amount'=>3,
[1]=>
'pid'=>8,
'amount'=>1,
)
伊谢尔伦2017-05-16 13:03:33
使用pid作為新數組的鍵值
$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'];
}
}
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);
已经自己解决,自己想太复杂了
我想大声告诉你2017-05-16 13:03:33
//代码如下,希望对你有帮助。
$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);