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

如何在单次排序中按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);

逻辑说明

  1. 动态选择排序键:根据每个元素的recipient字段,自动切换排序依据——User类型用userName,Location类型用locationName。
  2. null值兜底:优先判断是否存在null排序键,直接将null元素推至末尾,保证非空元素优先排序。
  3. 字符串比较:用strcmp()完成标准字典序排序,若需要忽略大小写,替换为strcasecmp()即可。

最终排序结果

执行代码后,数组会按以下顺序输出:

  1. id=4(User类型,userName:Fritz Kalkbrenner)
  2. id=1(User类型,userName:Max Mustermann)
  3. id=2(Location类型,locationName:Another Location)
  4. id=3(Location类型,locationName:Wow Much Location)
  5. id=5(Location类型,locationName:null)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:50:15