-2

I am using recursive function to walk through array elements.But failed to get correct counter.What i did.

$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);
        }
}

But for array structure like

arr1
arr2
    arr3
        arr4
   arr5
arr6

Output of my code is

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

While i needed

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

What i am doing wrong or what i understood wrong about recursion. If there is better way to do this then please advice. thanks in advance.

2 Answers 2

1

The variable $i changes only in the function and it doesn't affect variable outside of the function. When it's recursion, then it seems that it is in one function, but new variable $i is created for each call.

The simplest solution is pass value by reference. It's done by adding & before parameter $i in definition of function:

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

Second solution returning value of $i and assigning it as new value outside of called function:

$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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Warning: Invalid argument supplied for foreach()
thanks for the short explanation .It worked I understood my mistake
0

Change your if (count($item)) to if (is_array($item))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.