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 );
    
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)