我有以下数组结构,它是从数据库生成的:
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
个空格填充选项文本。
答案 0 :(得分:1)
如果您只想填充选项名称,可以使用RecursiveIteratorIterator::getDepth
并添加填充乘以当前深度:
$option_padding = str_repeat(" ", 4 * $cat->getDepth() );