jeetu
jeetu

Reputation: 23

recursive PHP function to retrive all the children for the specified category

I would like to write a recursive PHP function to retrive all the children for the specified category. I tried the one described here, but it didn't output what I have expected.

My categories table looks like this:

CREATE TABLE `categories` (
 `category_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
 `category_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_slug` varchar(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_parent` smallint(5) unsigned NOT NULL DEFAULT '0',
 `category_description_ro` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `category_description_en` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1

Bellow is an example of data in the table:

category id | category name | category_parent

1            Categoria 1            0        
2            Categoria 2            0        
3            Categoria 3            0        
4            Categoria 1.1          1        
5            Categoria 1.2          1        
6            Categoria 1.3          1        
7            Categoria 1.1.2        4 

I want to know how I print this recursively in PHP.

Upvotes: 0

Views: 549

Answers (5)

kba
kba

Reputation: 19466

Assuming your data has been initialized to an array $data.

$data = array(array("1", "Categoria 1", "0"),
        array("2", "Categoria 2", "0"),
        array("3", "Categoria 3", "0"),
        array("4", "Categoria 1.1", "1"),
        array("5", "Categoria 1.2", "1"),
        array("6", "Categoria 1.3", "1"),
        array("7", "Categoria 1.1.2", "4"));

You can use the following

function build_tree($data, $cat=0, $indent=0)
{
    $out = "";
    foreach($data as $entry)
    {
        if ($entry[2] != $cat)
            continue;

        $padding = str_repeat(' ',$indent);
        $out .= sprintf("%s<li>%s</li>\n", $padding, $entry[1]);

        if ($sub = build_tree($data, $entry[0], $indent+4))
            $out .= sprintf("%s<ul>\n%s%s</ul>\n", $padding, $sub, $padding);
    }
    return $out;
}

print build_tree($data);

The above will print

<li>Categoria 1</li>
<ul>
    <li>Categoria 1.1</li>
    <ul>
        <li>Categoria 1.1.2</li>
    </ul>
    <li>Categoria 1.2</li>
    <li>Categoria 1.3</li>
</ul>
<li>Categoria 2</li>
<li>Categoria 3</li>

Upvotes: 1

Zul
Zul

Reputation: 3608

What about this one:

<?php    
$result=mysql_query("SELECT * FROM categories");

// Builds the array lists with data from the categories table
while ($items = mysql_fetch_assoc($result))
{
    $categories['items'][$items['category_id']] = $items;
    $categories['parents'][$items['category_parent']][] = $items['category_id'];
}    

//the function
function category_tree($parent, $array)
{
   $return = "";

   if (isset($array['parents'][$parent]))
   {
      $return .= "<ul>";

       foreach ($array['parents'][$parent] as $itemId)
       {
          if(!isset($array['parents'][$itemId]))
          {
             $return .= "<li>".$array['items'][$itemId]['category_name']."</li> \n";
          }

          if(isset($array['parents'][$itemId]))
          {
             $return .= "<li>".$array['items'][$itemId]['category_name'];
             $return .= category_tree($itemId, $array);
             $return .= "</li>";
          }
       }
       $return .= "</ul>";
   }

   return $return;
}


echo category_tree(0, $categories);
?>

Upvotes: 1

Elen
Elen

Reputation: 2343

here is adopted/not tested version of my options hierarchy (if answer to both my questions is yes):

function GetOptions($parentSection,$level)
  { 
    $result = mysql_query('select category_id,category_name,category_parent from categories AS names where (category_parent='.$parentSection.') ORDER BY category_id;');
    $level_prefix=str_repeat('&nbsp;&nbsp;',$level);
    if($result)
    {   while ($row = mysql_fetch_array($result))
        {  
                $sec .= '<option value="'.$row['category_id'].'">'.$level_prefix.$star.$row['category_name'].'</option>';
                 GetOptions($row['category_id'],$level+1*2);}
        }
    }
    return $sec; $sec = '';
  }

and you call it as (don't forget SELECT tag if you use Options):

echo GetOptions(0,0); 

Upvotes: 0

bowlerae
bowlerae

Reputation: 944

Ok well since you said you want the results of a specific category.

Say the $category_id is 1

    function Subcats($category_id){
        $getsubcats = mysql_query("SELECT * FROM categories WHERE category_parent = $category_id");
$sub_cats = mysql_num_rows($getsubcats);

    if($sub_cats == 0){
    echo "There are no sub categories for this category";
    }

    else {

        while($rowsubcats = mysql_fetch_array($getsubcats)){

        $sub_cat_id = $rowsubcats['id'];
        $sub_cat_name = $rowsubcats['name'];
        // other row info

        echo "write what you want to display here<BR>";
        } // end loop for each sub cat
    } // end if subcats > 0
}

Upvotes: 0

trembon
trembon

Reputation: 768

Not tested, but think it should be something like this atleast

function PrintRecursive($sql, $id = 0){
    $query = mysql_query("SELECT category_id,category_name,category_parent FROM categories WHERE category_parent = {$id}", $sql);
    while($row = mysql_fetch_array($query)){
        echo $row['category_id'] ." | ". $row['category_name'] ." | ". $row['category_parent'] ."<br/>";
        PrintRecursive($sql, $row['category_parent']);
    }
}

Upvotes: 0

Related Questions