'PHP foreach loop on unknown depth multidimensional array
I have a multidimensional array consisting of a directory structure or a tree if you want, but how can I loop through this data when I don't know the depth of the array? Here is an example of how the array could look like
I want to go through each item here so that I can add the items to <ul>
and <li>
to get a "menu" kind off. Just like an file-explorer.
Tried using foreach
but that is kinda hard when you don't always know the depth of the array.
Solution 1:[1]
Create a recursive function that checks if the element is an array, then if it is - call the function again, otherwise create the list-item as normal.
function my_print($array) {
$output = "<ul>";
foreach ($array as $value) {
if (is_array($value)) {
$output .= "<li>".my_print($value)."</li>";
} else {
$output .= "<li>".$value."</li>";
}
}
$output .= "</ul>";
return $output;
}
With an array as
$array = ['value', 'value',
['array 1', 'array 1',
['array 2']],
['array with more depth',
['array deep',
['array deeper']]]
];
..the output will be (although not formatted - formatted here for visual comparing with the array),
<ul>
<li>value</li>
<li>value</li>
<li>
<ul>
<li>array 1</li>
<li>array 1</li>
<li>
<ul>
<li>array 2</li>
</ul>
</li>
</ul>
</li>
<li>
<ul>
<li>array with more depth</li>
<li>
<ul>
<li>array deep</li>
<li>
<ul>
<li>array deeper</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
- Live demo at https://3v4l.org/mTQHI
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Qirel |