PHP名称排序代码,按文字里的数字进行排序!

<?php

$names = array(
    "Apple 12 Pro Max",
    "Samsung Galaxy S21",
    "Apple 11 Pro",
    "OnePlus 9",
    "Google Pixel 5",
    "Xiaomi Mi 11",
);

// 自定义排序函数
function cmp($a, $b) {
    // 从字符串中提取数字
    preg_match('/\d+/', $a, $a_matches);
    preg_match('/\d+/', $b, $b_matches);
    $a_number = $a_matches[0];
    $b_number = $b_matches[0];
    // 比较数字
    if ($a_number == $b_number) {
        return strcmp($a, $b); // 数字相同,按名称排序
    } else {
        return $a_number - $b_number; // 按数字排序
    }
}

// 使用自定义排序函数进行排序
usort($names, "cmp");

// 输出排序结果
foreach ($names as $name) {
    echo $name . "<br>";
}

?>

 

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论