这是我的数组:
Array
(
[4] => Array
(
[0] => stdClass Object
(
[name] => fixed
[total_kms] => 200
)
)
[9] => Array
(
[0] => stdClass Object
(
[name] => Temo
[total_kms] => 550
)
)
[10] => Array
(
[0] => stdClass Object
(
[name] => mohamed mostafa
[total_kms] => 1273
)
)
[11] => Array
(
[0] => stdClass Object
(
[name] => ahmed mostafa
[total_kms] => 1122
)
)
)
我想像此表一样显示此数组,但要将此数组从最高编号到最低编号(仅限3个名称)进行排序
我在桌子上的代码
<table class="table">
<h4 class="text-muted">
Top3 drivers done most kilometers
</h4>
<hr>
<tbody>
<tr>
<th class="thead-dark">Driver</th>
for ($i=0; $i < count($driver_kms) ; $i++)
{
if ($driver_kms[$i]->name !='')
{
<td><?=$driver_kms[$i]->name?></td>
}
}
</tr>
<tr>
<th>Kms</th>
for ($i=0; $i < count($driver_kms) ; $i++)
{
if ($driver_kms[$i]->name !='')
{
<td><?=$driver_kms[$i]->total_kms?></td>
}
}
</tr>
</tbody>
答案 0 :(得分:0)
在单个查询中获得预期结果:
SELECT U.name, SUM(R.meters)
FROM users U, reservations R
WHERE U.id = R.driver_id
ORDER BY SUM(R.meters) DESC
LIMIT 3
OR
使用arsort($driver_kms)
对数组进行排序,然后将for循环限制为3个元素for ($i = 0; $i < 3; $i++) { ...
答案 1 :(得分:0)
替换
$users = User::select('name as driver_name','id as user_id')->get();
foreach ($users as $value) {
$driver_kms[$value->user_id] = DB::select("select users.name,SUM(reservations.meters) as total_kms from reservations left outer join ers on (reservations.driver_id=users.id) where zone_id = $url_or_id and driver_id = $value->user_id and reservations.meters !='' order by SUM(reservations.meters) DESC limit 3");
}
$driver_kms = call_user_func_array('array_merge', $driver_kms);
使用
$driver_kms = DB::select("select users.name, SUM(reservations.meters) as total_kms
from reservations left outer join users
on (reservations.driver_id = users.id)
where zone_id = $url_or_id and reservations.meters !=''
group by reservations.driver_id
order by SUM(reservations.meters) DESC limit 3");
答案 2 :(得分:-1)
只需使用http://php.net/manual/en/function.uasort.php 使用回调比较数组元素。