循环遍历数组并使用它构建导航菜单

时间:2015-03-10 16:54:10

标签: php arrays

我正在尝试建立一个导航'系统',其中类别和子类别存储在一个数组中。

这是数组:

$navigation = array(

'users' =>  array(

    'view'      =>  1,
    'edit'      =>  1,
    'delete'    =>  1,
    'list'      =>  1

),

'profiles'      =>  array(

    'view'      =>  4,
    'edit'      =>  4,

),

'projects'      =>  array(

    'new'       =>  3,
    'edit'      =>  3,
    'delete'    =>  1,
    'list'      =>  2,
    'mylist'    =>  3

)

);

使用这个数组,我想循环遍历每个项目,如果用户的等级等于或低于值(1,2,3),则显示相应的链接。 但我真的不知道如何开始。

希望这很清楚!

1 个答案:

答案 0 :(得分:0)

foreach ($navigation as $category) {

    // need to track if main categories have been output already
    $category_already_output = false;

    foreach ($category as $subcategory => $permission) {

        if ($current_user_permission_level <= $permission) {

            if ( ! $category_already_output ) {
                // output your html for this main category nav here
                $category_already_output = true;
            }

            // output your html for this subcategory here

        }
    }
}

编辑:以上假设您不希望在用户没有任何子类别的权限时显示主类别。如果要始终显示每个主要类别,则可以将其简化为:

foreach ($navigation as $category) {

    // output main category html here

    foreach ($category as $subcategory => $permission) {

        if ($current_user_permission_level <= $permission) {

            // output your html for this subcategory here

        }
    }
}