PHP数组和总和

时间:2016-02-24 15:40:26

标签: php arrays sum

这是我的阵列:

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 ))

我想得到这个,相同名字的总和:

11
坏:的 8
主叫:的 4

还要从最高金额到最低金额订购。

任何帮助?

1 个答案:

答案 0 :(得分:1)

你必须迭代每个元素并且:

  • 如果sums数组中没有键,则创建一个键
  • 否则将数字添加到上一笔金额
<?php

$array = array(
    1 => array('great' => 5),
    2 => array('great' => 3),
    4 => array('bad' => 5),
    5 => array('calling' => 40),
    6 => array('great' => 3),
    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()用于按降序值对总和进行排序。

这将打印出来:

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

Result in Codepad