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

PHP如何按Excel列排序规则对行标签字符串数组进行排序

问题原因

默认字符串比较逻辑是逐字符对比ASCII码,会把AB这类多字母列标排在单字母B前面,不符合Excel列规则:Excel列标本质是26进制计数,A=1、B=2...Z=26、AA=27,单字母列的权重远低于多字母列,所以B要排在AA、AB之前。

解决代码

首先实现列标转数字的辅助逻辑,排序时优先对比列标对应的数字,列标相同再对比行号:

// 辅助函数:将Excel列字母转为对应数字
function excelColumnToNumber(string $column): int
{
    $column = strtoupper($column);
    $num = 0;
    $length = strlen($column);
    for ($i = 0; $i < $length; $i++) {
        $num = $num * 26 + (ord($column[$i]) - ord('A') + 1);
    }
    return $num;
}

usort($rowTags, function ($item1, $item2) {
    // 拆分每个标签的列字母部分和行号部分
    preg_match('/^([A-Za-z]+)(\d+)$/', $item1, $m1);
    preg_match('/^([A-Za-z]+)(\d+)$/', $item2, $m2);
    
    $col1 = excelColumnToNumber($m1[1]);
    $col2 = excelColumnToNumber($m2[1]);
    $row1 = (int)$m1[2];
    $row2 = (int)$m2[2];
    
    // 先按列排序,列相同再按行排序
    return $col1 <=> $col2 ?: $row1 <=> $row2;
});

如果需要调整优先级先按行再按列,只要调换返回值里的对比顺序即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 20:24:05