我通过这个递归函数将所有中间类别从第n个孩子中获取到父级。但是当id改变变量时,$ cats连接到前一个结果。在执行第二个第n个子ID之前,我想它为null。 见下面的代码
function find_parent($cat_id,$conn){
static $cats;
if ($cat_id > 0){
$q = mysqli_query($conn,'SELECT pw_cat_pid FROM pw_categories WHERE pw_cat_id = ' . $cat_id) or die(mysqli_error($conn));
$r = mysqli_fetch_assoc($q);
$cats[] = $cat_id;
find_parent($r["pw_cat_pid"],$conn);
}
return $cats;
}
$sub_cat = array(5,122);
foreach($sub_cat as $value)
{
$cat = find_parent($value);
print_r($cat);
}
It showed below result:
If $sub_cat = 5
Array ( [0] => 5 [1] => 3 [2] => 1 )
If $sub_cat = 122
Array ( [0] => 5 [1] => 3 [2] => 1 [3] => 121 [4] => 97 [5] => 1 )
答案 0 :(得分:0)
不要使用静态变量,使用by-refrence来实现目标:
function find_parent($cat_id,$conn, &$cats=array()){
if ($cat_id > 0){
$q = mysqli_query($conn,'SELECT pw_cat_pid FROM pw_categories WHERE pw_cat_id = ' . $cat_id) or die(mysqli_error($conn));
$r = mysqli_fetch_assoc($q);
$cats[] = $cat_id;
find_parent($r["pw_cat_pid"],$conn,$cats);
}
return $cats;
}
$sub_cat = array(5,122);
foreach($sub_cat as $value)
{
$cat = find_parent($value,$conn);
echo "<pre>";
print_r($cat);
}