How to group subarrays using values from two columns then sum a third column's values?

前端 未结 2 715
渐次进展
渐次进展 2020-12-12 07:49

This is a section of my array:

[1] => Array
(
    [quantity] => 2
    [product_id] => 1
    [option_id] => 22
)

[2] => Array
(
    [quantity]         


        
2条回答
  •  眼角桃花
    2020-12-12 08:46

    You only need to build compound temporary keys and then overwrite the keys.

    By writing an initial element (null in this case) then deleting the element after the loop is finished, you ensure that the first key in the result array is 1.

    To avoid the "messiness" of the repeated long-winded compound key, you can save the the dynamic key as a variable in the first line inside of the foreach loop, then reference that variable in the three respective locations in the condition block.

    Code (Demo)

    $array = [
        1 => ['quantity' => 2, 'product_id' => 1, 'option_id' => 22],
        2 => ['quantity' => 2, 'product_id' => 2, 'option_id' => 22],
        3 => ['quantity' => 3, 'product_id' => 2, 'option_id' => 22],
        4 => ['quantity' => 1, 'product_id' => 2, 'option_id' => 25]
    ];
    
    $result = [null];  // create placeholding element
    foreach($array as $subarray){
        $composite_key = $subarray['product_id'] . '_' . $subarray['option_id'];
        if(!isset($result[$composite_key])){
            $result[$composite_key] = $subarray;  // first occurrence
        }else{
            $result[$composite_key]['quantity'] += $subarray['quantity'];  // not first occurrence
        }
    }
    $result=array_values($result);  // change from assoc to indexed
    unset($result[0]);  // remove first element to start numeric keys at 1
    var_export($result);
    

    Output:

    array (
      1 => 
      array (
        'quantity' => 2,
        'product_id' => 1,
        'option_id' => 22,
      ),
      2 => 
      array (
        'quantity' => 5,
        'product_id' => 2,
        'option_id' => 22,
      ),
      3 => 
      array (
        'quantity' => 1,
        'product_id' => 2,
        'option_id' => 25,
      ),
    )
    

提交回复
热议问题