Reputation: 2855
i'm referring this address for function olLiTree
PHP function that creates a nested ul li?
i have this array
$tree = array("A"=>array("B"=>array("C"=>"C","D"=>"D"),"E"=>array("F"=>"F","G"=>"G")));
but not able to use this function
function olLiTree($tree)
{
echo '<ul>';
foreach($tree as $item) {
if (is_array($item)) {
olLiTree($item);
} else {
echo '<li>', $item, '</li>';
}
}
echo '</ul>';
}
to generate
<ul>
<li>A</li>
<li>B
<ul>
<li>C</li>
<li>D</li>
</ul>
</li>
<li>E
<ul>
<li>F
</li>
</ul>
</li>
<ul>
<li>G</li>
</ul>
</ul>
can anybody help me to fix this? thanks..
Upvotes: 1
Views: 4313
Reputation: 522085
function olLiTree($tree) {
$out = '<ul>';
foreach($tree as $key => $value) {
$out.= '<li>';
if (is_array($value)) {
$out.= $key . olLiTree($value);
} else {
$out.= $value;
}
$out.= '</li>';
}
$out.= '</ul>';
return $out;
}
Always return
the final output, don't echo
it directly. You'll thank yourself one day when you find a situation where you don't want to echo
it immediately. :)
You might want to change the array structure to this, as it's less redundant (works with above code):
$tree = array('A', 'B', 'C' => array('CA', 'CB'), 'D');
Upvotes: 9
Reputation: 37905
By using something like this it should work (I did not test it, so hopefully I did not make any embarrassing mistakes):
function olLiTree($tree)
{
echo '<ul>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<li>', $key;
olLiTree($item);
echo '</li>';
} else {
echo '<li>', $item, '</li>'; // Or use $key here as well
}
}
echo '</ul>';
}
If you want to exactly match the given example you need to modify the array, since it does not match the result. (But I suppose that is not the problem)
Upvotes: 1