我有一个数组,想要生成选择框。我知道它应该使用递归,但不知道它是如何工作的。 我有一个用于生成嵌套列表的代码示例,但现在我正在寻找构建如下内容的方法:
<select>
<option value="1">Category1</option>
<option value="4">::SubCategory2</option>
<option value="2">::SubCategory1</option>
<option value="3">::::SubSubCategory</option>
</select>
我该怎么做?
Array
(
[0] => Array
(
[id] => 1
[name] => Category1
[parent] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[name] => SubCategory2
[parent] => 1
[children] => Array
(
)
)
[1] => Array
(
[id] => 2
[name] => SubCategory1
[parent] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => SubSubCategory
[parent] => 2
[children] => Array
(
)
)
)
)
)
)
)
function GenerateSet($nav, $tabs = "") {
$html = !strlen($tabs) ?
"\n".$tabs.'<ul class="categories">'."\n" :
"\n".$tabs.'<ul>'."\n";
foreach($nav as $page) {
$html .= $tabs." ".'<li id="cat-'.$page['id'].'">';
$html .= ' <a href="#">
<span class="linker">
<span class="title">'.$page['name'].'</span>
</span>
</a>';
if(isset($page['children'][0])) {
$html .= $this->GenerateSet($page['children'], $tabs." ");
}
$html .= '</li>'."\n";
}
$html .= $tabs.'</ul>'."\n";
return $html;
}
答案 0 :(得分:1)
试试这个。如果当前项目有子项,则增加级别,并通过相同的函数显示,否则,降低级别。
$array = array(
array(
'name' => 'Cat 1',
'children' => array(
array(
'name' => 'Subcat 1'
)
)
),
array(
'name' => 'Cat 2',
'children' => array(
array(
'name' => 'Sub2',
'children' => array(
array(
'name' => 'Sub3'
)
)
)
)
),
);
echo showTree($array);
function showTree($items, $level = 0) {
foreach ($items as $item) {
echo str_repeat(":", $level * 2) . $item['name'] . "<br />";
if (!empty($item['children'])) {
$level++;
showTree($item['children'], $level);
}
if ($level > 0) {
$level--;
}
}
}
答案 1 :(得分:0)
检查这个
<?php
$your_array = array(
'0' => array(
'id' => 1,
'name' => 'Category1',
'parent' => 0,
'children' => array
(
'0' => array
(
'id' => 4,
'name' => 'SubCategory2',
'parent' => 1,
'children' => array
(
)
),
'1' => array
(
'id' => 2,
'name' => 'SubCategory1',
'parent' => 1,
'children' => array
(
'0' => array
(
'id' => 3,
'name' => 'SubSubCategory',
'parent' => 2,
'children' => array
(
)
)
)
)
)
)
);
$select_str = '<select>';
foreach($your_array as $val)
{
$select_str .= '<option value="'.$val['id'].'" parent ="'.$val['parent'].'">'.$val['name'].'</option>';
if(is_array($val['children']))
{
$select_str .= implemt_recur($val['children']);
}
}
$select_str .= '</select>';
echo $select_str;
// implement recursion and make options here
function implemt_recur($array)
{
$sub_select_str = '';
if(!empty($array))
{
foreach($array as $arr)
{
$sub_select_str .= '<option value="'.$arr['id'].'" parent ="'.$arr['parent'].'">'.$arr['name'].'</option>';
if(is_array($arr['children']))
{
$sub_select_str .= implemt_recur($arr['children']);
}
}
}
return $sub_select_str;
}
?>