我做一個(gè)商城裡面有個(gè)採(cǎi)購表,採(cǎi)購表裡面有訂單,有些訂單和另一些訂單的商品是一樣的,然後裡面字段amount是訂單這個(gè)商品的購買數(shù)量,我想判斷如果這個(gè)訂單和某個(gè)商品id是一樣就疊加amount欄位的數(shù)量,該怎麼做?
array(
[0]=>
'pid'=>7,
'amount'=>1,
[1]=>
'pid'=>7,
'amount'=>2,
[2]=>
'pid'=>8,
'amount'=>1,
)
比如這數(shù)組,有2個(gè)pid值是一樣的,我就把他結(jié)合數(shù)值相加變成這一下數(shù)組
array(
[0]=>
'pid'=>7,
'amount'=>3,
[1]=>
'pid'=>8,
'amount'=>1,
)
使用pid作為新數(shù)組的鍵值
$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'];
}
}
寫個(gè)循環(huán),根據(jù)pid 判斷是否存在相同的然後合併,最後產(chǎn)生一個(gè)新的陣列OK
$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);
已經(jīng)自己解決,自己想太複雜了
//程式碼如下,希望對(duì)你有幫助。
$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);