将多维数组排序为特定值

时间:2018-10-09 03:01:40

标签: php sorting multidimensional-array

我有一个类似于以下的数组,并且必须通过row_order

对主数组和子数组进行排序
$all_menu_items = array_merge($main_menu, $sub_menu);

        $parent_items = array();
        $sub_items = array();
        foreach ($all_menu_items as $m1) {
            if ($m1['menu_parent'] == 0) {
                $parent_items[$m1['menu_id']] = $m1;
            }
        }

//        GROUP SUB MENU ITEMS BY PARENT MENU ITEM
        foreach ($all_menu_items as $m2) {
            if ($m2['menu_parent'] != 0) {
                $sub_items[$m2['menu_parent']][$m2['menu_id']] = $m2;
            }
        }

        foreach ($parent_items as $kp1 => $p1) {
            if (!empty($sub_items[$p1['menu_id']])) {
                $parent_items[$kp1]['sub_items'] = $sub_items[$p1['menu_id']];
            }
        }

这是$parent_items

的输出
[23] => Array
        (
            [menu_title] => Professional Review
            [menu_id] => 23
            [row_order] => 5
            [sub_items] => Array
                (
                    [28] => Array
                        (
                            [menu_title] => CPD Course Log
                            [menu_id] => 28
                            [menu_parent] => 23
                            [menu_level] => 2
                            [menu_icon] => fa-circle-o
                            [menu_path] => 404
                            [permission_id] => 725
                            [row_order] => 9
                        )

                    [31] => Array
                        (
                            [menu_title] => A Paper
                            [menu_id] => 31
                            [menu_parent] => 23
                            [menu_level] => 2
                            [menu_icon] => fa-circle-o
                            [menu_path] => pr-a-papers
                            [permission_id] => 720
                            [row_order] => 4
                        )

我尝试了此操作,但无法做到这一点,请帮助

usort($myArray, function($a, $b) {
    return $a['row_order'] <=> $b['row_order'];
});

1 个答案:

答案 0 :(得分:0)

usort($myArray, function($a, $b) {
    return $a['row_order'] <=> $b['row_order'];
});

这应该在array_merge之后适用。 在将foreach应用于数组之前