0

I am recursively searching a tree node for its parents, and then trying to return its parent categories in an array.

The function receives and passes itself an array of each parent which is finally returned.

Even though this array has elements, the statement before the return when viewed outside the function is nul.

To make it work, I just made the parameter by reference. But why is it always nul?

Here is my code:

function getParent($id,$parents){ // to work changed this to getParent($id,&$parents)

    if($id < 2) { // 1 is the Top of the Tree , so job is done
        return $string;    
    }

     $child = DB::fetchExecute((object)array( // pdo query for category to get parents
     'sql'   => "category",
     'values'=>  array($id),
     'single'=>  1,
     'debug' =>  0)
     );

    $parent = DB::fetchExecute((object)array( // pdo query for parents info
        'sql'   => "category",
        'values'=>  array($child->native_parent_category_id),
        'single'=>  1,
        'debug' =>  0)
    );
    $string[]= "<li>$parent->name ($parent->native_category_id)</li>
        ";        

    getParent($parent->native_category_id , $parents);    
}

// call function
$array = array();
$returnString = getParent($id,$string);

var_dump($returnString,$array); // will both be NULL, or if called by Reference $array has the goods

?>
4

2 回答 2

0

改变:

function getParent($id,$parents){

至:

function getParent($id,$parents, $string){

并改变:

getParent($parent->native_category_id , $parents);

至:

getParent($parent->native_category_id , $parents, $string);

的范围$string仅在函数运行时存在 - 因此,如果您重新运行该函数,它将重置其中的所有变量。每次重新运行时都需要发送变量。

于 2013-04-11T22:24:37.863 回答
0

我会$string在函数之前和函数内部声明,global $string;在顶部使用。

于 2013-04-11T22:30:02.010 回答