I have a table name category with following cols
cat_id | name | parent
1 | item 1 | 0
2 | item 2 | 1
3 | item 3 | 0
4 | item 4 | 1
5 | item 5 | 3
How i can display it in a menu like this
Item 1
> Item 2
> Item 4
Item 3
开发者_运维知识库 > Item 5
Please help
Here is the function that can be used:
// $current_cat_id: the current category id number
// $count: just a counter, call it as 0 in your function call and forget about it
// Gets the drop down list recurssively of categories //
function find_pages_recursive($current_cat_id, $count)
{
global $db; // the database object instance
static $option_results;
// if there is no current category id set, start off at the top level (zero)
if (!isset($current_cat_id))
{
$current_cat_id = 0;
}
$count++;
// query the database for the sub-categories of whatever the parent category is
$query = 'SELECT id, title from pages where parid = ' . $current_cat_id . ' order by id';
$get_options = $db->execute($query);
$num_options = $db->count_select();
// our category is apparently valid, so go ahead :P
if ($num_options > 0)
{
while (list($cat_id, $cat_name) = mysql_fetch_row($get_options))
{
// if its not a top-level category, indent it to show that its a child category
if ($current_cat_id != 0)
{
$indent_flag = '';
for ($x = 2; $x <= $count; $x++)
{
$indent_flag .= '----';
}
$indent_flag .= ' ';
}
$option_results[$cat_id] = $indent_flag . $cat_name;
// now call the function again, to recurse through the child categories
find_pages_recursive($cat_id, $count);
}
}
return $option_results;
}
How To Use It:
echo '<select name="pages" id="pages">' . "\n";
echo '<option value="">--Select Page--</option>' . "\n";
$get_options = find_pages_recursive(0, 0);
if (count($get_options) > 0)
{
foreach ($get_options as $key => $value)
{
$options .= "<option value=\"$key\"";
$options .= ">$value</option>\n";
}
}
echo $options;
echo '</select>' . "\n";
Make sure to connect to the database first :)
精彩评论