的foreach和2D的PHP数组 [英] Foreach and 2D Array in PHP

查看:87
本文介绍了的foreach和2D的PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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',
     ...
);

这篇关于的foreach和2D的PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆