努力在递归函数

时间:2017-12-13 10:08:27

标签: php arrays recursion

我正在使用递归函数来遍历数组元素。但是没能得到正确的计数器。我做了什么。

$i = 0 ;
$this->make_items($items,$i);
public function make_items($items,$i)
{
    foreach($items as $item){
        $i++;
        echo  '<position>'.$i.'</position>';    
        if(count($item['children'])){
                $this->make_items($item['children'],$i);
        }
}

但对于像

这样的数组结构
arr1
arr2
    arr3
        arr4
   arr5
arr6

我的代码输出

<postion>1</position>
<postion>2</position>
<postion>3</position>
<postion>4</position>
<postion>4</position>
<postion>3</position>

虽然我需要

<postion>1</position>
<postion>2</position>
<postion>3</position>
<postion>4</position>
<postion>5</position>
<postion>6</position>

我做错了什么或我理解错误的递归。 如果有更好的方法,请咨询。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

变量$i仅在函数中发生变化,并且不会影响函数外部的变量。当它递归时,它似乎在一个函数中,但为每个调用创建了新变量$i

最简单的解决方案是通过引用传递值。通过在函数定义中在参数&之前添加$i来完成此操作:

public function make_items($items,&$i) { /* the rest of code remains same*/ }

第二个解决方案返回$i的值并将其指定为被调用函数之外的新值:

$i = 0 ;
$this->make_items($items,$i); //now $i is still 0 but return value is 6

public function make_items($items,$i)
{
    foreach($items as $item){
        $i++;
        echo  '<position>'.$i.'</position>';    
        if(count($item['children'])){
                $i = $this->make_items($item['children'],$i); // assign new value of $i
        }
    return $i; // return actual value of $i
}

答案 1 :(得分:0)

将您的if (count($item))更改为if (is_array($item))