我有这段代码,它是具有多个选择的递归类别树;
我正在使用ezsql类,
$query = $db->get_results("SELECT * FROM categories");
function Cats($query, $mainid = 0)
{
foreach($query as $category)
{
if($category->maincategoryid == $mainid)
{
echo '<option>';
if($category->maincategoryid != 0){echo '-';}
echo $category->categorytitle.'</option>';
echo Cats($query,$category->categoryid);
}
}
}
echo '<select multiple>';
Cats($query);
echo '</select>';
我想像这样树,但连字符出现问题,连字符每个循环仅重复一次。
Sites
- Google
-- Gmail
-- Youtube
- Yandex
-- Mail
-- Yandisk
-- Maps
Program
- Graphic
-- Adobe
-- Corel Draw
- Browser
-- Internet Explorer
-- Firefox
-- Chrome
答案 0 :(得分:0)
我已经对代码进行了一些调整,请尝试以下方法:
function Cats($query, $mainid = 0, $level = 0)
{
foreach($query as $category)
{
if($category->maincategoryid == $mainid)
{
echo '<option>';
if($category->maincategoryid != 0){echo str_repeat('-', $level);}
echo $category->categorytitle;
echo '</option>';
echo Cats($query,$category->categoryid, ($category->maincategoryid === 0) ? 1 : ($level + 1));
}
}
}
echo '<select multiple>';
Cats($objects);
echo '</select>';