简体   繁体   English

PHP 嵌套数组到 HTML 列表中

[英]PHP nested array into HTML list

Trying to get to grips with PHP, but I have absolutely no idea how to do this.试图掌握 PHP,但我完全不知道如何做到这一点。

I want to take this array:我想拿这个数组:

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

and turn it into this into something like this in HTML:并将其转换为 HTML 中的类似内容:

  • Vehicle车辆
    • Car
      • Hatchback掀背车
      • Saloon沙龙
    • Van
    • Lorry货车
  • Person
    • Male男性
    • Female女性
  • Matter事情
    • Solid坚硬的
    • Liquid液体
    • Gas气体

Tried a number of solutions from searching, but cannot get anything to work at all.从搜索中尝试了许多解决方案,但根本无法获得任何工作。

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>";
}

Try something like:尝试类似:

<?php
function ToUl($input){
   echo "<ul>";

   $oldvalue = null;
   foreach($input as $value){
     if($oldvalue != null && !is_array($value))
        echo "</li>";
     if(is_array($value)){
        ToUl($value);
     }else
        echo "<li>" + $value;
      $oldvalue = $value;
    }

    if($oldvalue != null)
      echo "</li>";

   echo "</ul>";
}
?>

Code source: Multidimensional array to HTML unordered list代码来源:多维数组转HTML无序列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM