Fix (small?) Error in Recursive Function
Posted: Tue Aug 12, 2008 2:12 pm
Here's the recursive function that I'm messing with:
I call the function 3 times with the following three arrays as input:
I have this as output:
It should look like this:
The error only seems to occur if the parent element has any children. Why are there two entries for e, two for f, and two for a? Each is only added once to the output. Where are those extra ones coming from?
Code: Select all
function display($names, $spacer="y")
{
print_r($names); // Troubleshooting
foreach($names AS $named)
if(is_array($named))
{
echo "is array<br />"; // Troubleshooting
if($spacer=="y")
{
echo "spacer is y<br />"; // Troubleshooting
$dis .= substr($dis, 0, -6) . "\n<ul>\n";
$spacer = "n";
}
$dis .= display($named, "y");
}
else
{
echo "added $named to dis<br />"; // Troubleshooting
$dis .= "<li><a href=\"?$named\">" . $named . "</a></li>\n";
}
if($spacer=="n")
$dis .= "</ul></li>\n\n";
return $dis;
}Code: Select all
Array ( [0] => e [1] => Array ( [0] => f [1] => Array ( [0] => g ) ) )
Array ( [0] => a [1] => Array ( [0] => b ) [2] => Array ( [0] => c ) )
Array ( [0] => d )I have this as output:
Code: Select all
Array ( [0] => e [1] => Array ( [0] => f [1] => Array ( [0] => g ) ) ) added e to dis
is array
spacer is y
Array ( [0] => f [1] => Array ( [0] => g ) ) added f to dis
is array
spacer is y
Array ( [0] => g ) added g to dis
Array ( [0] => a [1] => Array ( [0] => b ) [2] => Array ( [0] => c ) ) added a to dis
is array
spacer is y
Array ( [0] => b ) added b to dis
is array
Array ( [0] => c ) added c to dis
Array ( [0] => d ) added d to dis
total output:
# e
# e
* f
* f
o g
# a
# a
* b
* c
# dCode: Select all
# e
* f
o g
# a
* b
* c
# d