PHP nested array into HTML list

有些话、适合烂在心里 提交于 2019-12-13 10:08:52

问题


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

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:

  • 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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/27786998/php-nested-array-into-html-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!