如何对PHP关联数组排序?token按price,subscription按yearly price
PHP关联数组按指定规则排序方案
原有代码问题分析
你之前的写法有两个核心问题:
- 用价格值作为数组键,不仅没必要,还会在出现相同价格时覆盖数据;
- 最后循环时错误地把价格键塞进了
$new_packs,而非保留原有的数组元素,导致结果完全不符合预期。
正确实现思路
PHP中对多维数组做自定义排序,用usort()函数最直接——它允许你通过回调函数定义排序规则,完全不需要修改原数组结构,直接按需求比较元素大小即可。
具体规则逻辑:
- 对每个元素提取排序基准值:
- 类型为
token时,取price字段数值 - 类型为
subscription时,取price['yearly']字段数值
- 类型为
- 在回调函数中比较两个元素的基准值,实现升序/降序排序(你的示例为升序)
完整代码实现
$packs = [ [ 'name' => 'starter', 'type' => 'token', 'price' => 199 ], [ 'name' => 'business', 'type' => 'subscription', 'price' => [ 'monthly' => 19, 'yearly' => 219, ] ], [ 'name' => 'professional', 'type' => 'subscription', 'price' => [ 'monthly' => 9, 'yearly' => 119, ] ], ]; // 自定义排序回调函数 usort($packs, function($a, $b) { // 获取元素a的排序基准值 $aSortValue = $a['type'] === 'token' ? $a['price'] : $a['price']['yearly']; // 获取元素b的排序基准值 $bSortValue = $b['type'] === 'token' ? $b['price'] : $b['price']['yearly']; // 升序排序规则:返回负数则a在前,正数则b在前,0则顺序不变 return $aSortValue - $bSortValue; }); print_r($packs);
执行后会得到你预期的排序结果:
[ [ 'name' => 'professional', 'type' => 'subscription', 'price' => [ 'monthly' => 9, 'yearly' => 119, ] ], [ 'name' => 'starter', 'type' => 'token', 'price' => 199 ], [ 'name' => 'business', 'type' => 'subscription', 'price' => [ 'monthly' => 19, 'yearly' => 219, ] ], ]
补充调整说明
如果需要改为降序排序,只需要把回调函数的返回值修改为$bSortValue - $aSortValue即可。
内容的提问来源于stack exchange,提问作者Tick Twitch
相关产品推荐
相关产品推荐

