如何返回从递归函数数组 [英] How to return array from recursive function

查看:312
本文介绍了如何返回从递归函数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到这一解决方案,我不为这个多少时间。所以,我要的是使函数,我给类ID,并返回这是它的子类类别所有的ID。

I couldn't find solution for this and I don't have much time for this. So what I want is to make function that I give category ID and it returns all ID's of categories which are it's child categories.

function getID($var) {
    $categories = array();

    function getChildren($id) {
        $result = mysql_query("SELECT * FROM categories WHERE parentID = '$id'");
        echo "<ul>";
        while ($row = mysql_fetch_array($result)) {
            echo "<li><a>{$row['ID']}</a>";
            $categories[] = $row['ID'];
            getChildren($row['ID']);
            echo "</li>";
        }
        echo "</ul>";
    }

    getChildren($var);
    return $categories;
}

我wan't存储在$类数组的一切。 $ var为类别ID,我给工作。当我把这个功能它打印的正是我want't列表中,但数组为空。

I wan't to store everything in $categories array. $var is category ID which I give to function. When I call this function it prints list of exactly what I want't but array is empty.

推荐答案

看来你有一个范围的问题。试试这个:

It seems you have a scope problem. Try this:

function getChildren(&$categories, $id) {
  $result = mysql_query("SELECT * FROM categories WHERE parentID = '$id'");
  echo "<ul>";
  while ($row = mysql_fetch_array($result)) {
    echo "<li><a>{$row['ID']}</a>";
    $categories[] = $row['ID'];
    getChildren($categories, $row['ID']);
    echo "</li>";
  }
  echo "</ul>";
}

function getID($var) {
  $categories = array();

  getChildren($categories, $var);
  return $categories;
}

这里是描述如何通过引用而不是按值传递PHP参考页。基本上,它说,它有一个&放大器的功能参数;在它的前面将通过参考,而不是按值传递

Here is the PHP reference page describing how to pass by reference instead of by value. Basically it says that any function parameter which has a & in front of it will be passed by reference instead of by value.

这篇关于如何返回从递归函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆