在PHP中按字母顺序对数组进行排序,然后按数字对数组进行排序?

时间:2019-07-10 08:24:37

标签: php arrays sorting

请参阅此帖子php-sort-array-alphabetically-then-numerically

它不能解决我的问题。

如果显示$test,我有一个数组名print_r($test)

Array
(
    [0] => Array
        (
            [hrid] => 1
            [masterroom] => B4-G-3
        )

    [1] => Array
        (
            [hrid] => 2
            [masterroom] => B4-G-1
        )

    [2] => Array
        (
            [hrid] => 7
            [masterroom] => B4-1-2
        )

    [3] => Array
        (
            [hrid] => 8
            [masterroom] => B4-1-1
        )

    [4] => Array
        (
            [hrid] => 9
            [masterroom] => B4-1-10
        )

    [5] => Array
        (
            [hrid] => 10
            [masterroom] => B4-G-10
        )
)

然后尝试以下操作(请参阅上面的链接的答案):

function myComparison($a, $b){
    if(is_numeric($a) && !is_numeric($b))
        return 1;
    else if(!is_numeric($a) && is_numeric($b))
        return -1;
    else
        return ($a < $b) ? -1 : 1;
} 
usort ( $test , 'myComparison' );

结果是:

Array
(
    [0] => Array
        (
            [hrid] => 1
            [masterroom] => B4-G-1
        )

    [1] => Array
        (
            [hrid] => 2
            [masterroom] => B4-G-3
        )

    [2] => Array
        (
            [hrid] => 7
            [masterroom] => B4-1-1
        )

    [3] => Array
        (
            [hrid] => 8
            [masterroom] => B4-1-2
        )

    [4] => Array
        (
            [hrid] => 9
            [masterroom] => B4-1-10
        )

    [5] => Array
        (
            [hrid] => 10
            [masterroom] => B4-G-10
        )
)

但是我希望它是:

Array
(
    [0] => Array
        (
            [hrid] => 1
            [masterroom] => B4-G-1
        )

    [1] => Array
        (
            [hrid] => 2
            [masterroom] => B4-G-3
        )

    [2] => Array
        (
            [hrid] => 10
            [masterroom] => B4-G-10
        )

    [3] => Array
        (
            [hrid] => 7
            [masterroom] => B4-1-1
        )

    [4] => Array
        (
            [hrid] => 8
            [masterroom] => B4-1-2
        )

    [5] => Array
        (
            [hrid] => 9
            [masterroom] => B4-1-10
        )

)

谢谢。

1 个答案:

答案 0 :(得分:0)

您应该查看是否可以更新PHP。您应该从5.5

开始使用
<?php

$array = [
  [
    "hrid" => 1,
    "masterroom" => "B4-G-3"
  ],
  [
    "hrid" => 2,
    "masterroom" => "B4-G-1"
  ],
  [
    "hrid" => 7,
    "masterroom" => "B4-1-2"
  ],
  [
    "hrid" => 8,
    "masterroom" => "B4-1-1"
  ], [
    "hrid" => 9,
    "masterroom" => "B4-1-10"
  ],
  [
    "hrid" => 10,
    "masterroom" => "B4-G-10"
  ]
];

$masterroom  = array_column($array, 'masterroom');
$hrid = array_column($array, 'hrid');

array_multisort($masterroom, SORT_NATURAL, $hrid, SORT_ASC, $array);

var_dump($array);

呼吸示例:https://3v4l.org/NaMqS PHP 5.5+ 呼吸示例:https://3v4l.org/Bc88G PHP 5.5之前