从foreach循环php获得5个最高值

时间:2016-03-16 12:48:37

标签: php arrays sorting for-loop

我在foreach中做了一个代码:

foreach ($queries as $record) {
    $total[] = $record->TotalTrans;
}

从这条记录我想确定前5个结果整数。

结果示例如下:

stdClass Object
(
    [Transactions] => A
    [TotalTrans] => 2
)
stdClass Object
(
    [Transactions] => B
    [TotalTrans] => 95
)
stdClass Object
(
    [Transactions] => C
    [TotalTrans] => 5
)
stdClass Object
(
    [Transactions] => D
    [TotalTrans] => 12
)
stdClass Object
(
    [Transactions] => E
    [TotalTrans] => 4
)

有没有办法在foreach中对它进行排序?谢谢

1 个答案:

答案 0 :(得分:3)

使用usort$queries数组进行排序:

usort
(
    $queries,
    function( $a, $b )
    {
        return $b->TotalTrans > $a->TotalTrans;
    }
);

usort使用用户定义的比较函数按值对数组进行排序:在您的情况下,只需比较->TotalTrans值。

现在你的数组是:

Array
(
    [0] => stdClass Object
        (
            [Transactions] => B
            [TotalTrans] => 95
        )
    [1] => stdClass Object
        (
            [Transactions] => D
            [TotalTrans] => 12
        )
    [2] => stdClass Object
        (
            [Transactions] => C
            [TotalTrans] => 5
        )
    [3] => stdClass Object
        (
            [Transactions] => E
            [TotalTrans] => 4
        )
    [4] => stdClass Object
        (
            [Transactions] => A
            [TotalTrans] => 2
        )
)

仅检索前5行:

$topFive = array_slice( $queries, 0, 5 );

编辑:

使用foreach()循环,您可以这样做:

foreach ($queries as $record)
{
    $total[] = $record->TotalTrans;
}

rsort( $total );
$topFive = array_slice( $total, 0, 5 );

rsort()是一个按值按相反顺序对数组进行排序的函数。