按值对数组和子数组进行排序

Sort array and child arrays by value

我有一个像这样的数组:

$array = array(
    4 => array(
         'position' => 0
         'children' => array(
         )
    ),
    2 => array(
         'position' => 0
         'children' => array(
            3 => array(
                'position' => 1
            )
            5 => array(
                'position' => 0
            )
         )
    )
)

我需要按键 'position' 对外部数组 (2 & 4) 进行排序,升序(0 向上),然后按它们各自的顺序对每个内部数组 ('children') 进行排序位置。

可能有 6 个主数组,有 6 个 'children' 个数组需要排序。

最好的方法是什么?

如果我正确理解你对问题的解释,下面的代码对你有用:

//sort the outer array
usort($array, function($a, $b) {
    return $a['position'] - $b['position'];
});
//sort childrens
foreach ($array as &$item) {
    usort($item['children'], function($a, $b) {
        return $a['position'] - $b['position'];
    });
}

无论如何,usort 是一个本机 php 函数,对于描述的情况非常方便。 http://php.net/manual/en/function.usort.php