You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多维数组按speed列(索引4)降序排序实现咨询

问题原因

你之前尝试的asort、rsort仅支持一维数组的简单排序,无法适配当前三维数组结构下指定子字段排序的需求,且asort第二个参数为排序类型标识,不能直接传入排序字段,因此无法达到预期效果。

适配现有逻辑的解决方案

你现有代码是按日期循环输出每日通行表格,最便捷的方式是在每日表格生成前,先收集当日所有有效记录,自定义排序后再遍历输出,不需要改动原有$myArray的生成逻辑,修改代码如下:

替换原有输出部分的代码

找到你循环日期内的输出逻辑,将原有的foreach($new_platelist as $wlPlate)相关代码替换为以下内容:

// 先收集当前日期的所有有效通行记录
$todayRecords = [];
foreach ($new_platelist as $wlPlate) {
    if (isset($myArray[$wlPlate][$dayCheck])) {
        $todayRecords[] = [
            'plate' => $wlPlate,
            'info' => $myArray[$wlPlate][$dayCheck]
        ];
    }
}

// 按speed字段(对应info子数组索引4)降序排序
usort($todayRecords, function($itemA, $itemB) {
    // 降序返回B - A,如需升序则改为返回A - B即可
    return $itemB['info'][4] <=> $itemA['info'][4];
});

// 遍历排序后的记录输出表格行
foreach($todayRecords as $record) {
    print "<tr>";
    print "<td>".$record['plate']."</td>";
    print "<td>".$record['info'][0]."</td>";
    print "<td>".$record['info'][1]."</td>";
    print "<td>".$record['info'][3]."</td>";
    print "<td>".$record['info'][4]."</td>";
    print "</tr>";
}

兼容低版本PHP的写法

如果你的PHP版本低于7.0,不支持太空船运算符<=>,可以将排序回调部分替换为:

usort($todayRecords, function($itemA, $itemB) {
    return $itemB['info'][4] - $itemA['info'][4];
});

如果需要对所有日期的通行记录全局按速度排序,只需提前遍历整个$myArray将所有记录拉平为二维数组,再用上述相同的usort逻辑排序即可。

内容的提问来源于stack exchange,提问作者preethi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:27:03