Jump to content

Recursive Function


seksislav

Recommended Posts

Hello,

 

I need to make a function that will display all categories and subcategories from a mysql table.

 

In the mysql the table there is something like this: cat_id, cat_root;

 

if cat_root is 0 -> it is a main category. Otherways it means that cat_roots is pointing to the root category. For example:

 

Category 1 ( id 1 | cat_id 0 )

    Product 1( id 2 | cat_id 1)

        SubProcut 1 (id 3 | cat_id 2)

Category 2 (id 4 | cat_id 0 )

 

and so on. I hope you get the picture.

 

I'm looking for a way to call all the categories for a <select>. What I've done so far is something like this:

 

function makeSelectCategories($id = 0 ,$str = '",$spacing=""){

 

      $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id;

 

      $r = mysql_query($q) or die(mysql_error());

 

      if(mysql_num_rows($r) == 0)

      return false;

 

      while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

 

          $str .= "<option>".$spacing.$row['cat_title']."</option>";

 

        $str .= makeSelectCategories($row['cat_id'],$str,$spacing." ");

 

        }

return $str;

 

}

 

echo "<select>";

echo makeSelectCategories();

echo "</select>";

 

I hope you get what I mean. Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/135332-recursive-function/
Share on other sites

try

function makeSelectCategories($id = 0, $spacing=""){

      $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id;

      $r = mysql_query($q) or die(mysql_error());
      $str = '';
      //if(mysql_num_rows($r) == 0)
      //return false;

       while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

          $str .= "<option>".$spacing.$row['cat_title']."</option>";

         $str .= makeSelectCategories($row['cat_id'], $spacing." ");

        }
return $str;

}

Link to comment
https://forums.phpfreaks.com/topic/135332-recursive-function/#findComment-705031
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.