如何从阵列中获得4个最大值

时间:2016-05-23 21:20:07

标签: php arrays

我正试图通过此查询从数据库中获取某些状态及其值

SELECT state, COUNT(*) c FROM user_track WHERE day  BETWEEN '16' and '24' AND 
viewed='aniket27' GROUP BY state HAVING c > 0;

这给我一个像这样的结果 - >

this is how query look likes

然后使用while循环我将所有数据添加到数组

$ar = array();
while( $fetch = mysqli_fetch_array($query)){
$ar[] = $fetch; }

这是打印后数组的外观。

this is how array looks

现在我想在一个新数组和休息状态下获得四个具有最大计数值的状态,并将它们的值放到另一个数组中我该如何实现呢?

这是我尝试过的事情

function maxN(array $numbers, $n)
{
    $maxHeap = new SplMaxHeap;
    foreach($numbers as $number) {
        $maxHeap->insert($number);
    }
    return iterator_to_array(
        new LimitIterator($maxHeap, 0, $n)
    );
}
print_r( maxN( $a, 4 ) );

为什么我的数组看起来像多维呢?

1 个答案:

答案 0 :(得分:2)

您可以对数组进行排序

usort($ar, function($a, $b){
    return strnatcmp($a['c'], $b['c']);
});

然后将其切片

$ar2 = array_slice($ar, 0, 4);

或者你可以改变你的SQL

SELECT state, COUNT(*) c FROM user_track
WHERE day BETWEEN '16' and '24' 
AND viewed = 'aniket27' 
GROUP BY state HAVING c > 0
ORDER BY c DESC

您的数据将以正确的顺序出现