如何忽略拼接的整数值,对PHP关联数组进行字母排序?
忽略前缀整数对PHP数组按字母排序
你的问题核心是忽略字符串开头的数字前缀,只对- 之后的文本部分进行字母排序,同时保留原数组的键值关联。直接用asort($array, SORT_STRING)无效,因为它会把整个字符串(包括前缀数字)作为排序依据。
解决方案:使用uasort()自定义排序规则
uasort()函数允许传入自定义比较回调,既能对数组值排序,又能保留原键名。我们可以在回调里提取每个字符串的文本部分,再进行比较:
$array = [ 125 => '3110 - with a string', 128 => '3009 - keep a string', 126 => '3111 - a string', 121 => '3114 - be a string', 122 => '3113 - last string', ]; // 自定义排序回调 uasort($array, function($a, $b) { // 提取 "- " 之后的文本部分 $textA = substr($a, strpos($a, ' - ') + 3); $textB = substr($b, strpos($b, ' - ') + 3); // 按标准字母排序(需不区分大小写可替换为strcasecmp) return strcmp($textA, $textB); }); // 输出结果 print_r($array);
代码说明
strpos($a, ' - '):定位字符串中-的位置,确保准确分割前缀与文本部分substr(..., +3):从-的下一个字符开始截取,得到纯文本内容strcmp():对两段纯文本执行标准字母排序逻辑uasort():完成排序后保留原数组的键名,完全匹配你期望的输出结构
执行代码后将得到目标结果:
[ 126 => '3111 - a string', 121 => '3114 - be a string', 128 => '3009 - keep a string', 122 => '3113 - last string', 125 => '3110 - with a string', ]
内容的提问来源于stack exchange,提问作者Sidra Sultana
相关产品推荐
相关产品推荐

