Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return array from recursive function

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;
}

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.

like image 444
LaKaede Avatar asked Dec 20 '22 08:12

LaKaede


2 Answers

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;
}

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.

like image 126
fredrik Avatar answered Feb 07 '23 10:02

fredrik


$categories only exists in the scope of get children. You could either pass it by reference as second parameter or create get children as a closure with use (&$categories)

like image 23
Fabian Schmengler Avatar answered Feb 07 '23 10:02

Fabian Schmengler