Search code examples
phparrayssum

PHP Array Group and sum


This is my array:

Array ( [1] => Array ( [great] => 5 ) [2] => Array ( [great] => 3 ) [4] => Array ( [bad] => 5 ) [5] => Array ( [calling] => 4) [6] => Array ( [great] => 3 ) [2] => Array ( [bad] => 3 ))

I want to get this, sum of same names:

great:11
bad:8
calling:4

And also to order from highest sum to lowest.

Any help?


Solution

  • You have to iterate over each element and:

    • if there is no key in the sums array, create a key
    • otherwise add the number to the previous sum
    <?php
    
    $array = array(
        1 => array('great' => 5),
        2 => array('great' => 3),
        4 => array('bad' => 5),
        5 => array('calling' => 40),
        6 => array('great' => 3),
    );
    
    $sums = array();
    
    foreach ($array as $key => $values) {
        foreach ($values as $label => $count) {
            // Create a node in the array to store the value
            if (!array_key_exists($label, $sums)) {
                $sums[$label] = 0;
            }
            // Add the value to the corresponding node
            $sums[$label] += $count;
        }
    }
    
    // Sort the array in descending order of values
    arsort($sums);
    
    print_r($sums);
    
    foreach ($sums as $label => $count) {
        print $label.': '.$count.' ';
    }
    

    arsort() is used to sort the sums by descending values.

    This will print this:

    Array
    (
        [calling] => 40
        [great] => 11
        [bad] => 5
    )
    calling: 40 great: 11 bad: 5
    

    Result in Codepad.