我在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中对它进行排序?谢谢
答案 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()
是一个按值按相反顺序对数组进行排序的函数。