doutui839638 2013-08-28 08:53
浏览 144
已采纳

PHP:如何在数组中保存递归函数的结果?

I have changed version of this recursive function... http://www.phpbuilder.com/articles/databases/mysql/handling-hierarchical-data-in-mysql-and-php.html

What I need is a way to save the returned value of this function in an array so that I can reverse the order of array elements. The function works well for me, but I need a way to save values. Here is the code...

function display_children($category_id, $level) {
  global $database;
  $result = mysql_query("SELECT * FROM parents WHERE id_roditelja='$category_id'") or die(mysql_error());
  $niz = array();
  while ($row = mysql_fetch_array($result)) {
    echo str_repeat('  ', $level) . $row['naziv'] . "<br/>";
    array_push($niz, display_children($row['parent_id'], $level + 1));
//this is one way I tried, and I get $niz with exact number of elements but each is null
//in this $niz array I need to store values of recursion
    var_dump($niz);
  }
}
  • 写回答

1条回答 默认 最新

  • duanaoyuan7202 2013-08-28 09:02
    关注

    I think you want this:

    function display_children/* <- this must be the same */($category_id, $level) {
      global $database;
      $result = mysql_query("SELECT * FROM parents WHERE id_roditelja='$category_id'") or     die(mysql_error());
      $niz = array();
      while ($row = mysql_fetch_array($result)) {
        $niz[] = str_repeat('  ', $level) . $row['naziv'] . "<br/>"; // we need to save this
        $niz = array_merge($niz, /* as this -> */display_children($row['parent_id'], $level + 1)); // array_merge doesn't take a reference so we need to store its result in $niz
      }
      return $niz;
    }
    

    if you want a tree like structure use array_push instead of array_merge. As noone seems to notice: His function can't return anything without a return statement !

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号