/ menu

menu

二级菜单

// 一次获取所有菜单项,按 parent 顺序排列,确保 parent 为 0 的一级菜单排在最前面
$rows_sorted_by_parent = Menu::find()
    ->select(['id', 'name', 'route', 'parent'])
    ->orderBy('parent')
    ->asArray()
    ->all();

$tree_2_level = [];
foreach ($rows_sorted_by_parent as $row) {
    if (!$row['parent']) {// 一级分类
        $tree_2_level[$row['id']] = $row;
    } else {// 二级分类
        $tree_2_level[$row['parent']]['children'][] = $row;
    }
}

return $tree_2_level;
// SELECT id,parent,title FROM category ORDER BY parent,sort,id;
$rows = [
    ['id' => 1, 'parent' => 6, 'title' => '分类1.1', 'route' => '', 'sort' => 0],
    ['id' => 2, 'parent' => 6, 'title' => '分类1.2', 'route' => '', 'sort' => 0],
    ['id' => 3, 'parent' => 7, 'title' => '分类2.1', 'route' => '', 'sort' => 0],
    ['id' => 4, 'parent' => 8, 'title' => '分类3.1', 'route' => '', 'sort' => 0],
    ['id' => 5, 'parent' => 9, 'title' => '分类4.1', 'route' => '', 'sort' => 0],
    ['id' => 6, 'parent' => 0, 'title' => '分类1', 'route' => '', 'sort' => 0],
    ['id' => 7, 'parent' => 0, 'title' => '分类2', 'route' => '', 'sort' => 0],
    ['id' => 8, 'parent' => 0, 'title' => '分类3', 'route' => '', 'sort' => 0],
    ['id' => 9, 'parent' => 0, 'title' => '分类4', 'route' => '', 'sort' => 0],
];
$rows_sorted_by_parent = array_sort($rows, 'parent', SORT_ASC);
//echo json_encode($rows_sorted_by_parent, JSON_UNESCAPED_UNICODE);

$tree_2_level = [];
foreach ($rows_sorted_by_parent as $row) {
    if (!$row['parent']) {// 一级分类
        $tree_2_level[$row['id']] = $row;
    } else {// 二级分类
        $tree_2_level[$row['parent']]['children'][] = $row;
    }
}

echo json_encode($tree_2_level, JSON_UNESCAPED_UNICODE);

function array_sort($array, $on, $order = SORT_ASC)
{
    $new_array      = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
                break;
            case SORT_DESC:
                arsort($sortable_array);
                break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}