gpt4 book ai didi

php - 按 php 和 mysql 表分类

转载 作者:可可西里 更新时间:2023-11-01 08:38:03 28 4
gpt4 key购买 nike

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

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

请帮忙

最佳答案

这里是可以使用的函数:

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

确保先连接到数据库:)

关于php - 按 php 和 mysql 表分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940199/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com