对象数组前5个唯一值

时间:2012-10-30 18:34:13

标签: php arrays

我有一组带有两个特定键/值对的数组。我要做的是获取由cause决定的前5个唯一qty值。这意味着它将按唯一值将cause键组合在一起,然后为每个原因总计qty个键,并返回前5个原因和每个原因的总数量。

这是print_r(array_values($ array))打印出来的内容。

Array ( 
[0] => Array ( [cause] => Other (please comment) [qty] => 0.417 ) 
[1] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.430 ) 
[2] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.430 ) 
[3] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.513 ) 
[4] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.513 ) 
[5] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.750 ) 
[6] => Array ( [cause] => Chem Out FC-DryStrAddTow [qty] => 0.750 ) 
[7] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.816 ) 
[8] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.816 ) 
[9] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.828 ) 
[10] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.828 ) 
[11] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.681 ) 
[12] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.681 ) 
[13] => Array ( [cause] => No Cause Selected [qty] => 0.918 ) 
[14] => Array ( [cause] => No Cause Selected [qty] => 0.918 ) 
[15] => Array ( [cause] => No Cause Selected [qty] => 0.926 ) 
[16] => Array ( [cause] => No Cause Selected [qty] => 0.937 ) 
[17] => Array ( [cause] => No Cause Selected [qty] => 0.809 ) 
[18] => Array ( [cause] => No Cause Selected [qty] => 0.809 ) 
[19] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.891 ) 
[20] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.891 ) 
[21] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.884 ) 
[22] => Array ( [cause] => Slitter Cut/Saw-Poor Cut [qty] => 0.884 ) ) 

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

<?php

// Total up the quantities
$totals = array();
$tally  = array();
foreach ($datapoints as $entry) {
    if (!isset($totals[$entry['cause']]) {
        $totals[$entry['cause']] = 0;
        $tally[$entry['cause']]  = 0;
    }
    $totals[$entry['cause']] += $entry['qty'];
    $tally[$entry['cause']]++;
}

// Sort them, 'descending' or 'reverse', so the larger entries are first
arsort($totals, SORT_NUMERIC);

// Take the first 5 entries from the sorted list
$top = array_slice($totals, 0, 5);

// Do something with it.
foreach ($top as $cause => $totalQty) {
    echo $cause . ': ' . $totalQty . ' with ' . $tally[$cause] . ' events' . PHP_EOL;
}

如果这些数据来自数据库,那么最好使用数据库和SQL,例如:

SELECT cause, SUM(qty) as totalQty, COUNT(qty) as tally
FROM data
GROUP BY cause
ORDER BY totalQty DESC
LIMIT 5;

而不是在php中加载所有数据和处理。

答案 1 :(得分:1)

如果使用php 5.3+,您可以在代码中使用闭包并排序(按数量递减)

usort($arary,function($a,$b){
    return $b['qty'] - $a['qty']
}

之后,您可以循环遍历数组并获取前5个唯一身份。