Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive function to get all the child categories

Here is what I'm trying to do: - i need a function that when passed as an argument an ID (for a category of things) will provide all the subcategories and the sub-sub categories and sub-sub-sub..etc. - i was thinking to use a recursive function since i don't know the number of subcategories their sub-subcategories and so on so here is what i've tried to do so far

function categoryChild($id) {

    $s = "SELECT * FROM PLD_CATEGORY WHERE PARENT_ID = $id";
    $r = mysql_query($s);

    if(mysql_num_rows($r) > 0) {

        while($row = mysql_fetch_array($r))
            echo $row['ID'].",".categoryChild($row['ID']);
    }
    else {
        $row = mysql_fetch_array($r);
        return $row['ID'];
    }
}

If i use return instead of echo, i won't get the same result. I need some help in order to fix this or rewrite it from scratch

like image 342
user253530 Avatar asked Mar 07 '10 23:03

user253530


2 Answers

I had a hard time trying to figure out your function. I think this will do what you want. It gets all the children of a category with ID $id, and also their children (thus getting the whole sub category, sub sub category effect that you wanted).

function categoryChild($id) {
    $s = "SELECT ID FROM PLD_CATEGORY WHERE PARENT_ID = $id";
    $r = mysql_query($s);

    $children = array();

    if(mysql_num_rows($r) > 0) {
        # It has children, let's get them.
        while($row = mysql_fetch_array($r)) {
            # Add the child to the list of children, and get its subchildren
            $children[$row['ID']] = categoryChild($row['ID']);
        }
    }

    return $children;
}

This function will return:

$var = array(
        'categoryChild ID' => array(
                'subcategoryChild ID' => array(
                        'subcategoryChild child 1' => array(),
                        'subcategoryChild child 2' => array()
                )
        ),
        'anotherCategoryChild ID' => array() # This child has no children of its own
);

It basically returns an array with the ID of the child and an array containing the IDs of its children. I hope this is of any help.

like image 124
Bruno De Barros Avatar answered Nov 15 '22 17:11

Bruno De Barros


database tree to multidimensional array

<?php
function getTree($rootid)
{
   $arr = array();

   $result = mysql_query("select * from PLD_CATEGORY where PARENT_ID='$rootid'");
   while ($row = mysql_fetch_array($result)) { 
     $arr[] = array(
       "Title" => $row["Title"],
       "Children" => getTree($row["id"])
     );
   }
   return $arr;
}
?>
like image 37
Matthew Avatar answered Nov 15 '22 17:11

Matthew