dongzen2675 2013-06-13 11:16
浏览 39

使用每个递归函数添加到数组[重复]

This question already has an answer here:

I want to add to an array when each recursive function is called. I have played around with it a few ways, but just getting error after error. This is about where I am up to, it should be enough to work out what I am trying to accomplish.

function structure($x, $structure = array()) {
$qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x");
$result = mysql_fetch_assoc($qry);
$cat = $result['parent_id'];
if($cat !=0) {
    structure($cat, $structure[] = $cat);
}
echo $cat.' >';
return $structure;
}

echo structure(22);
var_dump($structure);

So I am also trying to return the array as well, unsuccessfully. I am not sure how you return an array from a function either.

So I would appreciate help on how to add to an array with each recursive function and return the array outside of the function into a useable variable.

</div>
  • 写回答

1条回答 默认 最新

  • douqi3913 2013-06-13 11:59
    关注
    if($cat !=0) {
        $structure = structure($cat, $structure[] = $cat);
    }
    

    as structure() return a value, you need to set it to a variable, so this variable is fed on every call. And at the end :

    $whatever = structure(22);
    var_dump($whatever );
    
    评论

报告相同问题?