Here's what i've tried but the numbers is wrong and I don't know why
It should be 1, 2, 3, 4, 5, and etc..
Here is my PHP code:
function GetNavigations(SimpleXMLElement $element, $level = 0, $mrg = 0)
{
$value = trim((string) $element);
$children = $element->children();
$attributes = $element->attributes();
//echo '<ul>';
if(count($children) == 0 && !empty($value))
{
if($element->getName() == 'GroupName')
{
if($attributes['ParentId'] != '')
{
//$mrg = $level/2 * 10;
echo '<li>'.$mrg.'<a class="btngroup" href="load.php?active=menu&group_name_id='.$attributes['GroupNameId'].'">'.$element.'</a></li>';
}
}
}
if(count($children))
{
foreach($children as $child)
{
GetNavigations($child, $level+1, $mrg+1);
}
}
//echo '</ul>';
}
GetNavigations($child, $level+1, $mrg+1)
will pass the same value of $mrg
to all children of a node, however many children it has, because $mrg
is not being changed anywhere else inside that loop. Instead of $mrg+1
, you could pass ++$mrg
- or more readably, add $mrg++;
as the line before and just pass $mrg
.
However, you will still have the problem that the function only knows how many direct children have been displayed, not how many descendants - if you call GetNavigations
with an $mrg
value of 2
, and it displays 20 nested items, your next value of $mrg
will be 3
, not 23
! Although they all have the same name, each time you run the function, you have a new $mrg
variable.
To get around that, you can either:
$mrg
in by reference (by changing the function declaration to be function GetNavigations(SimpleXMLElement $element, $level = 0, &$mrg)
with the added &
, so that all copies of the function can write to the same variable.$mrg
out as the return
value of the function.I would probably prefer the second approach, as it's a bit clearer to anyone reading the code what's going on:
function GetNavigations(SimpleXMLElement $element, $level = 0, $mrg = 0)
{
/* [snip] */
if($element->getName() == 'GroupName')
{
// Increment counter, because we're displaying something
$mrg++;
/* [snip] */
}
/* [snip] */
if(count($children))
{
foreach($children as $child)
{
// Recurse, and get incremented value of counter
$mrg = GetNavigations($child, $level+1, $mrg);
}
}
/* [snip] */
// Let caller know where the counter has got to
return $mrg;
}