-4

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.

3
  • 5
    Where are the "solutions" you tried? What did "not work"? Commented Jan 5, 2015 at 20:05
  • 1
    use recursion and loop Commented Jan 5, 2015 at 20:08
  • 2
    possible duplicate of Multidimensional array to HTML unordered list Commented Jan 5, 2015 at 20:08

2 Answers 2

3

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>";
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'll try my best to implement it. Thank you for the help, much appreciated.
Update: This worked straight away, thank you so much!
This should also work for arrays that contain both arrays and static values. i.e. array("foo"=>array("a","b"),"bar","baz");
That's great! Thanks again. I can't upvote because my reputation is still low, but I accepted the answer.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.