我有以下数组结构,它是从数据库生成的:
Array
(
[0] => stdClass Object
(
[id] => 1
[parent] => 0
[children] => Array
(
[0] => stdClass Object
(
[id] => 2
[parent] => 1
[children] => Array
(
[0] => stdClass Object
(
[id] => 3
[parent] => 2
)
)
)
[1] => stdClass Object
(
[id] => 7
[parent] => 1
)
)
)
[1] => stdClass Object
(
[id] => 4
[parent] => 0
[children] => Array
(
[0] => stdClass Object
(
[id] => 5
[parent] => 4
[children] => Array
(
[0] => stdClass Object
(
[id] => 6
[parent] => 5
)
)
)
)
)
)
我想做的是在 HTML<select>
框中显示此信息,并使用正确的缩进来指示结构。因此,对于给定的示例,结果应如下所示:
- Select category
- Category 1
- Category 2
- Category 3
- Category 7
- Category 4
- Category 5
- Category 6
我目前正在使用 PHP 的RecursiveIteratorIterator()
类循环内容,该类可以输出所有内容,但我不知道如何包含缩进。这是我现在拥有的代码:
$html = '<select>';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree), RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $i => $cat)
{
if($cat->id != '')
{
$option = new self($this->_db, $cat->id);
$html.= '<option value="'.$cat->id.'"';
$html.= '>'.$option->name;
$html.= '</option>';
}
}
$html.= '</select>';
return $html;
谁能指出我正确的方向。本质上,我要做的就是按x
每个嵌套深度的空格填充选项文本。