的foreach和2D的PHP数组数组、foreach、PHP

2023-09-07 12:47:43 作者:孤酒独饮

$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['MapA'][2] = '/mult/kara.php';
$mainMenu['MapB'][2] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';

这是一个菜单中,1表示的主要部分,2表示子菜单。像:

This is a menu, 1 indicates the main part, 2 indicates the sub-menu. Like:

首页 地图 -MapA -MapB Contat 布拉

Home Map -MapA -MapB Contat Bla

我知道如何使用的foreach 但据我看到它采用的是一维数组。我必须做在上面的例子?

I know how to use foreach but as far as I see it is used in 1 dimensional arrays. What I have to do in the example above?

推荐答案

您需要嵌套两个的foreach 但是,有任何关于你的数据结构,可以轻松地表示什么是一个子项。地图与地图?我想一个人能明白这一点,但你必须写很多boilerlate的脚本进行排序的..考虑转型的数据,使其更接近你想要达到的目的。

You would need to nest two foreach BUT, there is nothing about your data structure that easily indicates what is a sub-item. Map vs. MapA? I guess a human could figure that out, but you'll have to write a lot of boilerlate for your script to sort that.. Consider restructuring your data so that it more closely matches what you are trying to achieve.

下面是一个例子。你也许可以想出一个更好的系统,但:

Here's an example. You can probably come up with a better system, though:

$mainMenu = array(
    'Home' => '/mult/index.php',
    'Map' => array(
        '/mult/kar.php',
        array(
            'MapA' => '/mult/kara.php',
            'MapB' => '/mult/karb.php'
        )
     ),
     'Contact' => '/mult/sni.php',
     ...
);