-1
我試圖在<select>
元素中實現以下輸出。html <select>多個級別
Mouses
Logitech
Red
White
Microsoft
Black
Keyboards
Logitech
Small size
Red
Green
Medium size
Black
正如您所看到的,可能存在不定級別。 在我的MySQL數據庫我創建了一個表類:
id
description
category_parent_id
和輸入是非常簡單的。
1 Mouses null
2 Logitech 1
3 Red 2
4 White 2
5 Keyboards null
6 Logitech 5
依此類推。正如你所看到的,當第一個類別被設置爲null
來識別原點時。
// Disables duplicated categories
$alreadyOutput = array();
foreach($categories as $category)
{
if(in_array($category->id, $alreadyOutput) == FALSE)
{
echo '<option value="' . $category->id . '">';
echo $category->description;
echo '</option>';
}
foreach($categories as $subCategory)
{
if($subCategory->category_parent_id == $category->id &&
in_array($subCategory->id, $alreadyOutput) == FALSE)
{
echo '<option value="' . $subCategory->id . '">';
echo ' ' . $subCategory->description;
echo '</option>';
}
}
}
有了這個代碼我的輸出是:
Mouses
Logitech
Red
White
Microsoft
Black
Keyboards
Logitech
Small size
Red
Green
Medium size
Black
而且我明白這是爲什麼。 首先,空間   
只做一次,應該根據級別增加。我試圖通過創建兩個函數來提出解決方案。第一個決定類別需要做的步驟數量以達到原點。
function stepsToJump($categories, $id, $category_parent_id)
{
$parentPosition = 0;
$position = 0;
foreach($categories as $i => $category)
{
if($category->id == $category_parent_id)
$parentPosition = $i;
if($category->id == $id)
$position = $i;
}
return $position - $parentPosition;
}
function htmlSpaces($amount)
{
$html = ' '; // default
for($i = 0; $i < $amount; $i++)
$html .= ' ';
return $html;
}
而與此,我以這種方式實現:
echo htmlSpaces(stepsToJump($categories,
$subCategory->id,
$category->id)) . $subCategory->description;
可惜的是我的輸出是錯誤的。
Mouses
Logitech
Red
White
Microsoft
Black
Keyboards
Logitech
Small size
Red
Green
Medium size
Black
FYI:有一種叫做'optgroup'的問題 – adeneo 2015-04-02 16:29:06
問題是什麼?再讀一遍。 我不想使用'optgroup',因爲我希望用戶能夠選擇頭部類別。 – Linesofcode 2015-04-02 16:30:19
@Linesofcode你沒有說你試圖避免'optgroup'。 – 2015-04-02 16:33:09