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

标签 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"
                )

        )

)

而且我想根据内部内容对 $MY_ARRAY 直接子项进行排序, 理想情况下,顺序为 start_year、start_month、end_year、end_month。我想我可以以某种方式使用 array_multisort(),但我不知道如何使用。有谁知道如何处理这个问题?

谢谢。

编辑: 正如它所显示的那样,解决方案既好又简单,我不知道的是,在回调比较函数的比较过程中,您可以进入更深层次的结构 - 所以如果您比 lvl-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');

关于PHP:使用给定的字段顺序按比 1 级维度值更深的维度值对多数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820514/

相关文章:

Python 3 排序忽略 __lt__ 和 __eq__

php根据条件从一个数组创建多个数组

windows - 从计算机名称列表中获取登录用户

php - 限制 foreach 只显示 10 行数据?

algorithm - 从多个排序数组中选择前 n 个项目

Java初学者: Array Bubble Sort

php - 保护和加密客户端和服务器之间的连接

php - 更新mysql中一列中的两个不同字符串

php - Yii2 - Filsh OAuth2 服务器安装

php - Laravel5 : TokenMismatchException in compiled. php 第 3123 行: