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.
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.
$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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With