子类由php和mysql表组成

时间:2010-10-15 07:14:58

标签: php mysql categories

我有一个包含以下列的表名类别

cat_id     |    name     |   parent   
 1         |    item 1   |     0
 2         |    item 2   |     1
 3         |    item 3   |     0
 4         |    item 4   |     1
 5         |    item 5   |     3

我如何在这样的菜单中显示它

Item 1

   > Item 2
   > Item 4

Item 3

    > Item 5

请帮忙

1 个答案:

答案 0 :(得分:2)

以下是可以使用的功能:

// $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;
}

如何使用

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";

确保首先连接到数据库:)