如何在单次排序中按recipient字段规则排序PHP多维数组
PHP多维数组自定义排序实现
完全可以通过单次排序实现需求,无需拆分数组。利用PHP的usort()函数配合自定义比较逻辑,就能同时满足「按recipient选择排序字段」「null值元素排末尾」的要求。
实现代码
// 待排序数组 $array = [ [ "id" => 1, "recipient" => "User", "userName" => "Max Mustermann", "locationName" => "Test Location" ], [ "id" => 2, "recipient" => "Location", "userName" => "Susi Mustermann", "locationName" => "Another Location" ], [ "id" => 3, "recipient" => "Location", "userName" => "Susi Mustermann", "locationName" => "Wow Much Location" ], [ "id" => 4, "recipient" => "User", "userName" => "Fritz Kalkbrenner", "locationName" => "Good Music" ], [ "id" => 5, "recipient" => "Location", "userName" => "Paul Kalkbrenner", "locationName" => null ], ]; // 自定义排序逻辑 usort($array, function($a, $b) { // 根据recipient确定排序键 $aKey = $a['recipient'] === 'User' ? $a['userName'] : $a['locationName']; $bKey = $b['recipient'] === 'User' ? $b['userName'] : $b['locationName']; // 处理null值:将含null的元素排到末尾 if ($aKey === null && $bKey !== null) return 1; if ($bKey === null && $aKey !== null) return -1; if ($aKey === null && $bKey === null) return 0; // 非null值按字典序排序,如需忽略大小写可替换为strcasecmp() return strcmp($aKey, $bKey); }); // 输出排序结果 print_r($array);
逻辑说明
- 动态选择排序键:根据每个元素的
recipient字段,自动切换排序依据——User类型用userName,Location类型用locationName。 - null值兜底:优先判断是否存在
null排序键,直接将null元素推至末尾,保证非空元素优先排序。 - 字符串比较:用
strcmp()完成标准字典序排序,若需要忽略大小写,替换为strcasecmp()即可。
最终排序结果
执行代码后,数组会按以下顺序输出:
- id=4(User类型,userName:Fritz Kalkbrenner)
- id=1(User类型,userName:Max Mustermann)
- id=2(Location类型,locationName:Another Location)
- id=3(Location类型,locationName:Wow Much Location)
- id=5(Location类型,locationName:null)
内容的提问来源于stack exchange,提问作者Florianb
相关产品推荐
相关产品推荐

