PHP 中的 Foreach 和二维数组 [英] Foreach and 2D Array in PHP

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

问题描述

$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:

首页
地图
-地图A
-地图B
联系我们
布拉

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 但是,您的数据结构没有任何内容可以轻松指示什么是子项.地图与 MapA?我想人类可以解决这个问题,但是您必须为脚本编写大量样板文件来对其进行排序.. 考虑重构您的数据,使其更接近您想要实现的目标.

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

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

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