问题
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
- Car
- 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