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.
3 Answers 3
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.
-
Same problem as with Naryls answer, if you do it this way you have to pass a reference to the original array (as fabs answer suggests)Gerald Schneider– Gerald Schneider2013年03月15日 08:14:08 +00:00Commented Mar 15, 2013 at 8:14
-
oh, thanks. It works! Only one thing getChildren($categories, $var); should be $this->getChildren($categories, $var);LaKaede– LaKaede2013年03月15日 08:22:00 +00:00Commented Mar 15, 2013 at 8:22
-
Oh, you have it in a class - that was not in the question. If course then you need the
$this->
as well.fredrik– fredrik2013年03月15日 08:24:35 +00:00Commented Mar 15, 2013 at 8:24
$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)
function getChildren($id, $categories)
should work.
The array was out of scope, so the function didn't touch the one you are returning. It created a new local $categories inside the function.
-
1This will return an empty array as well. The function
getChildren()
will work with a copy of the empty array, the original array will not be touched. If you want the function to add to the original array you have tu usefunction getChildren($id, &$categories);
.Gerald Schneider– Gerald Schneider2013年03月15日 08:10:54 +00:00Commented Mar 15, 2013 at 8:10
it prints list of exactly what I want't but array is empty
it prints and its empty!?!?