2013-04-11 141 views
0

我递归搜索树的父节点,然后尝试返回其父类别的数组。PHP函数返回空值

该函数接收并传递一个最终返回的每个父代的数组。

尽管此数组包含元素,但在函数外部查看时返回之前的语句是nul

为了使它工作,我只是通过引用做出参数。但为什么总是nul

这里是我的代码:

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 

?> 
+2

如果'$ id <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范围只存在于功能,因为它运行 - 所以,如果你重新运行该功能,它会在它重置所有的变量。每次重新运行时都需要发送变量。

0

我会声明$string之前的功能,并在里面的功能,在顶部使用global $string;