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

前端 未结 2 713
渐次进展
渐次进展 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,
      ),
    )
    
    0 讨论(0)
  • 2020-12-12 08:52

    One possible solution to your problem consists of the following steps:

    1. Use a double for loop to examine every element in the array with every element after it.
    2. Compare the product and option ids and if they match.
      1. Sum the quantities into the former item.
      2. Unset the latter item.
      3. Use array_values to make the array compact again.
      4. Break out of the nested loop.

    Code:

    # The sample array.
    $array = [
        ["quantity" => 2, "product_id" => 1, "option_id" => 22],
        ["quantity" => 2, "product_id" => 2, "option_id" => 22],
        ["quantity" => 3, "product_id" => 2, "option_id" => 22],
        ["quantity" => 1, "product_id" => 2, "option_id" => 25]
    ];
    
    # Iterate over every element of the array.
    for ($i = 0, $l = count($array); $i < $l; $i++) {
        # Iterate over every element after the current one in the array.
        for ($j = $i + 1; $j < $l; $j++) {
            # Compare the product and option ids.
            $sameProduct = $array[$i]["product_id"] == $array[$j]["product_id"];
            $sameOption = $array[$i]["option_id"] == $array[$j]["option_id"];
    
            # Check whether two items have the same ids.
            if ($sameProduct && $sameOption) {
                # Add the value of the item at index j to the one at index i.
                $array[$i]["quantity"] += $array[$j]["quantity"];
    
                # Unset the array at index j.
                unset($array[$j]);
    
                # Make the array compact.
                $array = array_values($array);
    
                # Break out of the loops.
                break 2;
            }
        }
    }
    

    Note: Your question shows no effort made in your part. I'm assuming you are completely lost and have no idea what to do and that's the only reason I'm answering. If you have made any effort that did not work as expected include it in your question, as that will prompt other users to answer too and perhaps give you better answers than mine.

    0 讨论(0)
提交回复
热议问题