【问题标题】:Sort array recursively | multidimensional array sort递归排序数组 |多维数组排序
【发布时间】:2018-07-11 07:45:02
【问题描述】:

我需要使用sort(),但我注意到它不会对多维数组进行排序。

我创建了这个函数,但发现它只适用于二维数组。我需要sort() 所有嵌套数组。

这就是现在的样子:

public static function sortArray($array) : array {
    sort($array);
    foreach ($array as &$index) {
        if (is_array($index)) {
            sort($index);
        }
    }
    return $array;
}

有没有办法对所有子孙进行检查和排序?

【问题讨论】:

  • array_multisort 不起作用?
  • array_multisort

标签: php arrays sorting multidimensional-array php-7.1


【解决方案1】:

最好你可以发布你的数组。所以我们有一些想法。无论如何,如果这个例子解决了你的问题。试试这个:-

Array
(
[item-1] => Array
    (
        [id] => 1
        [title] => Item 1
        [order] => 3
    )

[item-2] => Array
    (
        [id] => 2
        [title] => Item 2
        [order] => 2
    )

[item-3] => Array
    (
        [id] => 3
        [title] => Item 3
        [order] => 1
    )
)
usort($array, 'sort_by_order ');
function sort_by_order ($a, $b)
{
    return $a['order'] - $b['order'];
}
        Or
array_multisort(array_column($array, 'order'),SORT_ASC,$array);

或者这个链接可能会帮助你:- https://blog.jachim.be/2009/09/php-msort-multidimensional-array-sort/comment-page-1/ 希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多