Skip to content Skip to sidebar Skip to footer

PHP Nested Array Into HTML List

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', 'salo

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

Solution 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


Post a Comment for "PHP Nested Array Into HTML List"