dounielong7728 2017-10-09 12:39
浏览 326
已采纳

当值具有字符串和数字时,如何对数组进行排序

I have an array i want to sort it into ascending order.

Below is array i have.

Array

[0] => 101.6mm x 101.6mm 
[1] => 50.8mm x 50.8mm 
[3] => 76.2mm x 76.2mm 
[4] => 100mm x 100mm 
[5] => 15mm x 15mm 
[6] => 20mm x 20mm 
[8] => 25mm x 25mm 
[10] => 30mm x 30mm 
[12] => 40mm x 40mm 
[13] => 50mm x 50mm 
[14] => 60mm x 60m 
[15] => 80mm x 80mm 

Thanks in advance

  • 写回答

3条回答 默认 最新

  • drk7700 2017-10-09 13:33
    关注

    You just need to write custom string parts comparison function for usort():

    $products = [
                    "101.6mm x 101.6mm",
                    "50.8mm x 50.8mm",
                    "76.2mm x 76.2mm",
                    "100mm x 100mm",
                    "15mm x 15mm",
                    "20mm x 20mm",
                    "50mm x 50.2mm",
                    "25mm x 25mm",
                    "30mm x 45mm",
                    "30mm x 30mm",
                    "40mm x 40mm",
                    "50mm x 50mm",
                    "60mm x 60m",
                    "80mm x 80mm",
        ];
    
    usort($products,
        function($a, $b) {
            list($vals_a, $vals_b) = [explode('x', $a), explode('x', $b)];
            $vals_a[0] = preg_replace('/(\s|mm)/mui', '',$vals_a[0]);
            $vals_a[1] = preg_replace('/(\s|mm)/mui', '',$vals_a[1]);
            $vals_b[0] = preg_replace('/(\s|mm)/mui', '',$vals_b[0]);
            $vals_b[1] = preg_replace('/(\s|mm)/mui', '',$vals_b[1]);
            if ($vals_a[0] < $vals_b[0])
                return -1;
            elseif ($vals_a[0] > $vals_b[0])
                return +1;
            else {
                if ($vals_a[1] < $vals_b[1])
                    return -1;
                elseif ($vals_a[1] > $vals_b[1])
                    return +1;
                else return 0;
            }
        });
    
    var_dump($products);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,