如何使用PHP过滤数组?

时间:2015-09-18 15:17:46

标签: php arrays

的print_r($菜单);给出以下输出:

Array
    (
        [0] => Array
            (
                [name] => Politics
                [action] => politics
            )

        [sub_menu2] => Array
            (
                [0] => Array
                    (
                        [name] => submenu2
                        [action] => politics
                    )
                 [1] => Array
                    (
                        [name] => submenu3
                        [action] => sport
                    )

            )

    )

我期望的过滤后的数组是:

Array
    (
        [0] => Array
            (
                [name] => Politics
                [action] => politics
                [sub_menu2] => Array
               (
                 [0] => Array
                    (
                        [name] => submenu2
                        [action] => politics
                    )
                 [1] => Array
                    (
                        [name] => submenu3
                        [action] => sport
                    )

               )
            )
    )

我的代码是:

$filteredMenu = array();
$unique = array();
$index = 0;
$index2 = 0;
foreach ($menus as $key => $menu) {
    $pm = $menu['Menu']['name'];
    if (isset($unique[$pm])) {                
        if (!empty($menu['sub_menus']['name'])) {
            $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu'][] = $temp;
        }
         if(!empty($menu['sub_sub_menus']['name'])){
                 $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu']['sub_menu2'][] = $temp;
            }
    } else {
        if ($key != 0)
            $index++;
        $unique[$pm] = 'set';
        $temp = array('name' => $pm, 'action' => $menu['Menu']['action']);
        $filteredMenu[$index]['menu'] = $temp;
        if (!empty($menu['sub_menus']['name'])) {
            $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu'][] = $temp;
        }
         if(!empty($menu['sub_sub_menus']['name'])){
                 $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu']['sub_menu2'][] = $temp;
            }
    }
}

我可以过滤以包装菜单下的所有和菜单。但我无法在子菜单下包装所有二级子菜单。我花了很多时间来解决但失败了。

1 个答案:

答案 0 :(得分:1)

您的PHP代码与您的数组不同。从哪里找到

args = parser.parse_args()
profile_name = args.profile_name

这将显示错误未定义索引:菜单

我认为你必须申请更多条件。 我不确定应用下面的代码。我认为这将解决您的问题。

$pm = $menu['Menu']['name'];