php多级数组按su子数组值排序


php multilevel array sort by su-sub-sub array value

我有一个多级数组,如下

array( 
    (int)0=>array(
              'User' => array(
        'PostType' => array(
            'PHP' => array(
                'id' => '2',
                'type_title' => 'Core Questions',
                'type_description' => 'none',
                'type_sort_order' => '7'
                'Post'=>array(
                    ......
                    ),
            ),
            'ASP' => array(
                'id' => '1',
                'type_title' => 'Core Questions',
                'type_description' => 'none',
                'type_sort_order' => '1'
                'Post'=>array(
                    ......
                    ),
            ),
        ),
)));

我获取了一个用户,其帖子按postType分类
postType具有type_sort_order字段
我想按type_sort_order字段对子数组PostType进行排序
使得CCD_ 5在CCD_ 6之前
我试过按以下启动

usort($arr,function(){
                return  ($a[0]['User']['PostType']['post_sort_order'] < $b[0]['User']['PostType']['post_sort_order'])?1:-1;
            });

以及许多其他排序,但没有得到正确的结果

array_multisort将工作。解决方案如下:

$list = //Your array
$sortOrders = array();
foreach ($list[0]['User']['PostType'] as $postType) {
    $sortOrders[] = $postType['type_sort_order'];
}
array_multisort($sortOrders, $list[0]['User']['PostType']);

这将获取数组中的所有排序顺序,排序顺序与起始数组相同。在两个数组上使用array_multisort将对第一个数组进行排序,并将新的顺序应用于第二个数组,从而得到您想要的结果。

您正在寻找http://php.net/manual/en/function.array-multisort.php

通过PostType循环并获取所有type_sort_order,并放置在一个单独的数组中。然后使用该数组作为array_multi_sort 的参数

您似乎只是在尝试对子数组PostType进行排序,所以只需传递该数组