PHP:使用给定的字段顺序对多级数组进行排序,使其比级别1维度值更深

jav*_*web 5 php arrays sorting multidimensional-array

我的阵列:

$MY_ARRAY = 
Array
(
    [0] => Array
        (
            [0] => 2861
            [1] => Array
                (
                    [start_month] => 6
                    [start_year] => 1970
                    [end_month] => 12
                    [end_year] => 1990
                    [experience_info] => "Practically a random string"
                )

        )

)
Run Code Online (Sandbox Code Playgroud)

我希望$MY_ARRAY通过内部内容对直接孩子进行排序,理想情况是以start_year,start_month,end_year,end_month的顺序排列.我想我可以用array_multisort()某种方式,但我不知道如何.有谁知道如何处理这个?

谢谢.

编辑:当它出现时,解决方案很简单,我不知道的是,在回调比较函数的比较中你可以进入更深层次的结构 - 所以如果你的lvl-1索引比你的更深层保持不变(我的情况)那是怎么做的:)

Ale*_*ruk 1

为此,您可以使用uasort函数:

function compare_callback($arr1, $arr2) {
    $start_year1 = $arr1[1]['start_year'];
    $start_year2 = $arr2[1]['start_year'];

    $start_month1 = $arr1[1]['start_month'];
    $start_month2 = $arr2[1]['start_month'];

    $end_year1 = $arr1[1]['end_year'];
    $end_year2 = $arr2[1]['end_year'];

    $end_month1 = $arr1[1]['end_month'];
    $end_month2 = $arr2[1]['end_month'];

    return ($start_year1 === $start_year2)
        ? (($start_month1 === $start_month2)
            ? (($end_year1 === $end_year2)
                ? (($end_month1 === $end_month2)
                    ? 0
                    : (($end_month1 < $end_month2) ? -1 : 1))
                : (($end_year1 < $end_year2) ? -1 : 1))
            : ($start_month1 < $start_month2) ? -1 : 1)
        : (($start_year1 < $start_year2) ? -1 : 1);
}

uasort($array, 'compare_callback');
Run Code Online (Sandbox Code Playgroud)