0

Sorry for this dumb question, but I really don't see what I'm doing wrong :(

I've this 2 functions within a class

function getParentCat($treeTag) 
{

    // fetch some db data
    $parentId = $row->Fparent_id;
    $parentArray = array();

    if ($parentId > 0) {
        $parentArray = $this->iterateParentCat($parentArray,$parentId);

            // print_r here show nothing, no array, nothing !

    }  else {
        $parentArray[] = $treeTag;
    }
    return $parentArray;
}

And the second function :

function iterateParentCat($parentArray,$parentId)
{
    // Fetch some db data
    $parentArray[] = $row->Ftag;

    if ($row->Fparent_id > 0) {
        $this->iterateParentCat($parentArray,$row->Fparent_id);

    }  else {

         // print_r here show a perfect, beautiful array

        return $parentArray;
    }
}

So it seems I've lost the array (not just the content, the whole array) between the 2 functions. It must be a simple thing... but I can't see it ! Soooory :)

2
  • 1
    return $this->iterateParentCat($parentArray,$row->Fparent_id);? Commented Apr 1, 2020 at 8:44
  • Thank you !!! I knew it was something really obvious ! My mind is fogged... a 1000 thanks ! Commented Apr 1, 2020 at 8:50

2 Answers 2

3

Create reference variable.

function getParentCat($treeTag) 
    {

        // fetch some db data
        $parentId = $row->Fparent_id;
        $parentArray = array();

        if ($parentId > 0) {
            $parentArray = $this->iterateParentCat(&$parentArray,$parentId);

                // print_r here show nothing, no array, nothing !

        }  else {
            $parentArray[] = $treeTag;
        }
        return $parentArray;
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You are using recursive logic (calling itself to go deeper), but you do nothing with the result you get from it. Every call you go deeper, the $parentArray from the one-level-up doesn't exists. So it adds values to the array, returns it, but then the one-upper does nothing with it :)

function iterateParentCat($parentId)
{
    // Fetch some db data
    $data = [$row->Ftag];

    if ($row->Fparent_id > 0) {
        $recursiveData = $this->iterateParentCat($row->Fparent_id);
        $data = array_merge($data, $recursiveData); // add the data from one down (and one down (and one down))
    }

    return $data;
}

Alternatively, you could do iterateParentCat(&$parentArray,$parentId), telling php that the while recursive path now worth by reference, they will now will update the same variable. IMO this isn't the way go, by-reference should be avoided if you can as it can make simple thing very complex, very fast.

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.