我正在处理类别和子类别部分,我想在其各自的类别下显示所有子类别。
它类似于Wordpress类别子类别显示。我想在Codeigniter中运行这个东西。
下面是我的数组
Array
(
[0] => Array
(
[name] => 1 Category
[children] => Array
(
[0] => Array
(
[name] => 1 Sub Category
)
[1] => Array
(
[name] => 2nd 1 Sub Category
)
)
)
[1] => Array
(
[name] => 6 Category
[children] => Array
(
[0] => Array
(
[name] => 6 Sub Category
[children] => Array
(
[0] => Array
(
[name] => 2 Sub Category
[children] => Array
(
[0] => Array
(
[name] => 7 Sub Category
)
)
)
)
)
)
)
)
我的愿望是:
1 Category
- 1 Sub Category
- 2nd 1 Sub Category
6 Category
- 6 Sub Category
- 2 Sub Category
- 7 Sub Category
另一个期望的输出:
<select>
<option>1 Category</option>
<option>- 1 Sub Category</option>
<option>- 2nd 1 Sub Category</option>
<option>6 Category</option>
<option>- 6 Sub Category</option>
<option>- - 2 Sub Category</option>
<option>- - - 7 Sub Category</option>
</select>
我希望我清楚我的问题和期望的输出。
答案 0 :(得分:2)
我创建了一个返回ul,li结果的函数输入。试试这个..
get_category($array);
function get_category($array) {
echo '<ul>';
foreach($array as $category) {
echo '<li>';
echo $category['name'];
if(isset($category['children'])) {
get_category($category['children']);
}
echo '</li>';
}
echo '</ul>';
}
选择输出的更新
echo '<select>';
get_category($array);
echo '</select>';
function get_category($array, $prefix = '') {
foreach($array as $category) {
echo '<option>';
echo $prefix . $category['name'];
echo '</option>';
if(isset($category['children'])) {
get_category($category['children'], $prefix.'- ');
}
}
}