PHP将数组嵌套到HTML列表中 [英] PHP nested array into HTML list

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

问题描述

试图掌握PHP,但是我完全不知道如何做到这一点.

Trying to get to grips with PHP, but I have absolutely no idea how to do this.

我想要这个数组:

$things = array('vehicle' => array('car' => array('hatchback', 'saloon'),'van','lorry'),
                'person' => array('male', 'female'),
                'matter' => array('solid', 'liquid', 'gas'),
            );

并将其转换为HTML中的类似内容

and turn it into this into something like this in HTML:

  • 车辆
    • 汽车
      • 掀背车
      • 沙龙
      • Vehicle
        • Car
          • Hatchback
          • Saloon
          • 固体
          • 液体
          • 气体

          尝试了多种搜索解决方案,但根本无法解决任何问题.

          Tried a number of solutions from searching, but cannot get anything to work at all.

          推荐答案

          您正在寻找的东西称为递归.下面是一个递归函数,如果array键的值也是一个数组,则该递归函数将自行调用.

          What you are looking for is called Recursion. Below is a recursive function that calls itself if the value of the array key is also an array.

          function printArrayList($array)
          {
              echo "<ul>";
          
              foreach($array as $k => $v) {
                  if (is_array($v)) {
                      echo "<li>" . $k . "</li>";
                      printArrayList($v);
                      continue;
                  }
          
                  echo "<li>" . $v . "</li>";
              }
          
              echo "</ul>";
          }
          

          这篇关于PHP将数组嵌套到HTML列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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