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

PHP实现关联数组的自定义规则排序(非字母序)

PHP自定义规则排序关联数组的实现方案

嘿,这个自定义排序的需求我之前也处理过,咱们来一步步实现它~

首先先明确需求:我们需要把数组分成两大组,Text开头的项排在最前面,并且按Text A到Text E的顺序排列;剩下的**Lorem Ipsum项排在后面**,按末尾的数字1→2→3→4的顺序排序,同时要保留原数组的键值关联。

实现思路

  1. 先区分元素所属的分组,给Text组更高的排序优先级;
  2. 同组内分别应用不同的排序规则:Text组按字符串自然顺序排序,Lorem Ipsum组提取末尾数字按数值升序排序;
  3. 使用uasort函数(而非usort),因为它能保留关联数组的键值对应关系。

完整代码实现

$arr = [
    '1' => 'Lorem Ipsum 1',
    '2' => 'Lorem Ipsum 3',
    '3' => 'Lorem Ipsum 2',
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '7' => 'Lorem Ipsum 4',
    '8' => 'Text D',
    '9' => 'Text E',
];

// 自定义排序回调,用uasort保留键值关联
uasort($arr, function($a, $b) {
    // 判断当前元素是否属于Text组(PHP 8.0+写法)
    $isTextA = str_starts_with($a, 'Text');
    $isTextB = str_starts_with($b, 'Text');

    // 跨组排序:Text组永远排在前面
    if ($isTextA !== $isTextB) {
        return $isTextA ? -1 : 1;
    }

    // 同组内排序逻辑
    if ($isTextA) {
        // Text组按字符串自然顺序排序(刚好匹配A-E的需求)
        return strcmp($a, $b);
    } else {
        // Lorem Ipsum组提取末尾数字,按数值排序
        preg_match('/\d+$/', $a, $matchesA);
        preg_match('/\d+$/', $b, $matchesB);
        $numA = (int)$matchesA[0];
        $numB = (int)$matchesB[0];
        return $numA - $numB;
    }
});

// 打印验证结果
print_r($arr);

低版本PHP兼容说明

如果你的PHP版本低于8.0,str_starts_with函数不支持,可以替换成substr的写法:

// 替换原有的str_starts_with判断
$isTextA = substr($a, 0, 4) === 'Text';
$isTextB = substr($b, 0, 4) === 'Text';

输出结果

运行代码后,你会得到和期望完全一致的数组:

Array
(
    [4] => Text A
    [5] => Text B
    [6] => Text C
    [8] => Text D
    [9] => Text E
    [1] => Lorem Ipsum 1
    [3] => Lorem Ipsum 2
    [2] => Lorem Ipsum 3
    [7] => Lorem Ipsum 4
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:19:10