php - Recursive data output
768
$dirs = array(
'root_dir' => array(
'sub_dir_1' => array(
0 => 'file'
),
'sub_dir_2' => array(
0 => 'file'
),
'sub_dir_3' => array(
0 => 'file_1',
1 => 'file_2',
2 => 'file_3'
)
),
);
$render = function($dirs) use (&$render) {
echo "<ul>";
foreach ($dirs as $parent => $children) {
if (is_string($parent) === true) {
echo "<li>$parent</li>";
$render($children);
} else {
echo "<li>$children</li>";
}
}
echo "</ul>";
};
$render($dirs);
Output
<ul>
<li>root_dir</li>
<ul>
<li>sub_dir_1</li>
<ul>
<li>file</li>
</ul>
<li>sub_dir_2</li>
<ul>
<li>file</li>
</ul>
<li>sub_dir_3</li>
<ul>
<li>file_1</li>
<li>file_2</li>
<li>file_3</li>
</ul>
</ul>
</ul>
Needed output
<ul>
<li>
root_dir
<ul>
<li>
sub_dir_1
<ul>
<li>file</li>
</ul>
</li>
<li>
sub_dir_2
<ul>
<li>file</li>
</ul>
</li>
<li>
sub_dir_3
<ul>
<li>file_1</li>
<li>file_2</li>
<li>file_3</li>
</ul>
</li>
</ul>
</li>
</ul>
What I am doing wrong ?
Answer
Solution:
Should be:
Otherwise your children are outside of the parent
<li>
.Answer
Solution:
@Niet spotted the mistake but I would go about this a slightly different way:
is_string
returnstrue
orfalse
, so no need for the===
comparison.echo
ing all over the place, I opted to build the string all in one go andecho
it at the end. This allows the output of$render($children)
to be concatenated within theforeach
loop</li>
in your finalecho
statement - I removed it.Hope it is of some use to you.