thinkphp5 - How does thinkphp operate if there are related arrays in the array, extract the values ​​and add them together?
仅有的幸福
仅有的幸福 2017-05-16 13:01:33
0
4
634

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,
    )
仅有的幸福
仅有的幸福

reply all(4)
伊谢尔伦

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']; 
    }
}
刘奇

Write a loop, judge whether there are the same ones based on pid, merge them, and finally generate a new array OK

phpcn_u1582
$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

我想大声告诉你

//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);       
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template