如何生成动态多维数组菜单 [英] How to generate menu from dynamic multidimensional array

查看:142
本文介绍了如何生成动态多维数组菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有数组到这里。我离开了一些地图和文件,这应该是足以让我的观点。没有最大深度到数组所以有可能会更大。

Lets say I have the array down here. I left out a few maps and files as this should be enough to make my point. There is no max depth to the array so there could be even more.

Array
(
    [media] => Array
        (
            [documents] => Array
                (
                    [0] => add.php
                )    
            [music] => Array
                (
                    [albums] => Array
                        (
                            [0] => add.php
                        )    
        )    
    [overview] => Array
        (
            [0] => overview.php
        )
) 

我想获得的东西这样的:

What I would like to get is something like the following:

<ul>
    <li>Media
        <ul>
            <li>Documents
                <ul>
                    <li><a href="/media/documents/add.php">Add</a></li>
                </ul>
            </li>

            <li>Music
                <ul>
                    <li>Albums
                        <ul>
                            <li><a href="/media/music/albums/add.php">Add</a></li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>

    </li>Overview
        <ul>
            <li><a href="/overview/overview.php">Overview</a></li>
        </ul>
    </li>
</ul>

我发现<一个href=\"http://stackoverflow.com/questions/11747156/php-create-navigation-menu-from-multidimensional-array-dynamically\">php创建多维数组的导航菜单动态的,但IMO接受的答案有相当大量的垃圾,结果是不太什么,我需要的。如果你想知道是如何产生的阵列,请让我知道。

I found php create navigation menu from multidimensional array dynamically but imo the accepted answer has quite a lot garbage and the result isn't quite of what I need. If you would like to know how the array is generated please let me know.

在此先感谢我的帮助

推荐答案

您需要使用通过你的阵列循环递归函数。事情是这样的:

You need to use a recursive function that loops through your array. Something like this:

function outputMenu(array $array, $baseUrl = '/')
{
    $html = '';
    foreach ($array as $key => $item)
    {
        if (is_array($item))
        {
            $html .= '<li>'.$key.'<ul>';
            $html .= outputMenu($item, $baseUrl.$key.'/');
            $html .= '</ul></li>';
        }
        else
        {
            $html .= '<li><a href="'.$baseUrl.$item.'">'.ucfirst(substr($item, 0, -4)).'</a></li>';
        }
    }
    return $html;
}

echo outputMenu($array);

这篇关于如何生成动态多维数组菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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