0

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?

4
  • That doesn't look like your full array, it's missing Array[0]. Commented Feb 24, 2016 at 15:41
  • 1
    Please provide the full, correct array, as well as what you have tried. There's several problems with your array that make it clear this is not your actual array. Commented Feb 24, 2016 at 15:44
  • 1
    It would be much easier if you post the complete code, if that array comes from a DB you can do that directly in the SQL query Commented Feb 24, 2016 at 15:44
  • My array has 448 lines, and it's start from 1. Isn't from SQL,it's making inside the loop $c[$i]=array($ime=>$zbir); Where $ime is great, bad, calling, and $zbir is 5,3,5,4,3,3 Commented Feb 24, 2016 at 15:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.