PHP:如何按优先级对多维数组进行排序
按优先级对多维PHP数组排序的解决方案
嘿,这个场景我太熟悉了!你的数组结构有点特别——$arr['fruits']里的每个元素都是只包含一个水果键的关联数组,要按每个水果的priority字段排序,咱们用PHP的usort()函数就能轻松搞定,下面是具体步骤:
核心思路
usort()允许我们自定义排序规则,关键是要从每个子元素里提取出priority值来做比较。因为每个$arr['fruits']的子元素是类似['banana' => [...]]的单键数组,我们可以用current()函数直接取出这个键对应的详细数组,再获取priority字段。
完整代码示例
方式1:PHP7.4+ 箭头函数(更简洁)
// 先定义你的数组 $arr['fruits'][0]['banana']['color'] = 'yellow'; $arr['fruits'][0]['banana']['qty'] = '50'; $arr['fruits'][0]['banana']['priority'] = 3; $arr['fruits'][1]['apple']['color'] = 'red'; $arr['fruits'][1]['apple']['qty'] = '75'; $arr['fruits'][1]['apple']['priority'] = 1; $arr['fruits'][2]['grape']['color'] = 'purple'; $arr['fruits'][2]['grape']['qty'] = '100'; $arr['fruits'][2]['grape']['priority'] = 5; // 按priority升序排序 usort($arr['fruits'], fn($a, $b) => (int)current($a)['priority'] - (int)current($b)['priority']); // 测试输出 print_r($arr['fruits']);
方式2:兼容旧版本PHP的匿名函数
// 排序逻辑 usort($arr['fruits'], function($a, $b) { $priorityA = (int)current($a)['priority']; $priorityB = (int)current($b)['priority']; return $priorityA - $priorityB; });
代码说明
current($a):取出当前子元素里唯一的水果数组(比如['color' => 'yellow', ...])- 转成
(int)是为了避免字符串比较的坑(虽然你的priority是数字,但保险起见处理一下更稳妥) - 如果需要降序排序,只需要把减法反过来:
$priorityB - $priorityA
排序后你会得到这样的顺序:
- apple(priority=1)
- banana(priority=3)
- grape(priority=5)
内容的提问来源于stack exchange,提问作者MultiDev
相关产品推荐
相关产品推荐

