如何从PHP中的递归函数计算xml的元素?

时间:2013-02-16 07:45:00

标签: php recursion simplexml

这是我尝试的但数字是错误的,我不知道为什么

enter image description here

它应该是1,2,3,4,5等。

这是我的PHP代码:

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>';
}

1 个答案:

答案 0 :(得分:1)

GetNavigations($child, $level+1, $mrg+1)会将$mrg的相同值传递给节点的所有子节点,无论它有多少个子节点,因为$mrg在该循环内的任何其他地方都没有被更改。而不是$mrg+1,您可以传递++$mrg - 或者更可读,将$mrg++;添加为之前的行,然后通过$mrg

但是,如果您使用GetNavigations $mrg2来调用$mrg,那么您仍然会遇到这样的问题:该函数只知道显示了多少直接子项,而不知道有多少后代。 },它显示20个嵌套项,您的下一个3值将是23,而不是$mrg!虽然它们都具有相同的名称,但每次运行该函数时,都会有一个新的$mrg变量。

要解决这个问题,您可以:

  • 通过引用传递function GetNavigations(SimpleXMLElement $element, $level = 0, &$mrg)(通过使用添加的&将函数声明更改为$mrg,以便函数的所有副本都可以写入同一个变量。
  • return的新值作为函数的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; } 值传递出去。

我可能更喜欢第二种方法,因为对于阅读代码的人来说,它会更清楚:

{{1}}