你必須遍歷每個元素:
- 如果總和數組中沒有鑰匙,創建密鑰
- 否則將號碼添加到先前的總和
<?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。
這並不像你全陣列,它缺少數組[0]。 – Here2Help
請提供完整,正確的數組,以及您嘗試過的內容。你的數組有幾個問題使得它清楚這不是你的* actual *數組。 –
如果您發佈的完整代碼,如果該數組來自一個數據庫,你可以做到這一點直接在SQL查詢 – Asur