简体   繁体   English

PHP数组组和总和

[英]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 极好: 11
bad: 8 差: 8
calling: 4 致电: 4

And also to order from highest sum to lowest. 并按从最高到最低的顺序排序。

Any help? 有什么帮助吗?

You have to iterate over each element and: 您必须遍历每个元素,并且:

  • if there is no key in the sums array, create a key 如果sums数组中没有键,请创建一个键
  • 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),
    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. arsort()用于按降序对总和进行排序。

This will print this: 这将打印此:

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

Result in Codepad . 结果进入键盘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM