如何打开一个嵌套数组使用PHP一个HTML列表? [英] How do I turn a nested array into a HTML list using PHP?

查看:133
本文介绍了如何打开一个嵌套数组使用PHP一个HTML列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  嵌套数组嵌套HTML

我如何把一个数组转换成HTML中使用保留阵列原有结构< UL> <李> 标签?下面是一个数组变量,我可能需要处理的样本。

How do I turn an array into HTML retaining the arrays original structure using <ul> and <li> tags? Below is a sample of an array variable I might need to process.

Array
    (
        [1] => Array
            (
                [parent_id] => 0
                [name] => books
                [children] => Array
                    (
                        [3] => Array
                            (
                                [parent_id] => 1
                                [name] => romans
                                [children] => Array
                                    (
                                        [4] => Array
                                            (
                                                [parent_id] => 3
                                                [name] => erotic
                                            )

                                    )

                            )

                    )

            )

        [2] => Array
            (
                [parent_id] => 0
                [name] => technics
            )

    )

感谢您!

推荐答案

您可能需要某种形式的云n级深入到你的阵列,在每个级别做一些等待处理递归函数的。你可以指望层次深你正在使用各种方法的数量,但这里是在正确的方向一推:

You probably want some sort of recursive function that goes n levels deep into your array, doing some proccessing at each level. You can count the number of levels deep you are using various methods but here is a push in the right direction:

$var = array('your array',0);
function printArray($array,$depth){
    foreach($array as $item){
        //Print your opening HTML
        if(is_array($item))
            //This is where your nested HTML will be printed
            printArray($item,$depth+1);
        //Print your closing HTML

    }
}

printArray($var);

正如你可以看到,函数调用自身传递子阵列本身,每次加一个深度。

As you can see, the function calls itself passing the child array to itself, adding one to the depth each time.

编辑,在repsonse您的评论,如果你想要显示的数据以不同的顺序,试试你的洗牌code周围一点点。见下图:

Edit, in repsonse to your comment, if you want the data to display in a different order, try shuffling your code around a little. See below:

function nested($list){
   foreach($list as $k) {
      if(!isset($k['children'])){ 
          echo $k['name'].'<br>';              
      }else{
          echo $k['name'].'<br>';
          nested($k['children']);
      }   
   }
}

这篇关于如何打开一个嵌套数组使用PHP一个HTML列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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