使用表从数组中构建层次结构-PHP
我在下面的场景中遇到了困难,我有一个带有类别的数组,因此类别可以有子类别,子类别可以有无限多个子类别。现在我正努力实现以下目标,但我就是无法实现 我在下面的结构中有一个数组使用表从数组中构建层次结构-PHP,php,html,Php,Html,我在下面的场景中遇到了困难,我有一个带有类别的数组,因此类别可以有子类别,子类别可以有无限多个子类别。现在我正努力实现以下目标,但我就是无法实现 我在下面的结构中有一个数组$items Array ( [0] => Array ( [label] => Main Cat [id] => 29 [parent_id] => 19 ) [1] =>
$items
Array
(
[0] => Array
(
[label] => Main Cat
[id] => 29
[parent_id] => 19
)
[1] => Array
(
[label] => Main Cat
[id] => 17
[parent_id] => 19
)
[2] => Array
(
[label] => Main Cat
[id] => 20
[parent_id] => 19
[items] => Array
(
[0] => Array
(
[label] => Child Level 1
[id] => 21
[parent_id] => 20
)
[1] => Array
(
[label] => Child Level 1
[id] => 22
[parent_id] => 20
[items] => Array
(
[0] => Array
(
[label] => Child Level 2
[id] => 27
[parent_id] => 22
[items] => Array
(
[0] => Array
(
[label] => Child Level 3
[id] => 28
[parent_id] => 27
)
)
)
)
)
[2] => Array
(
[label] => Child Level 1
[id] => 23
[parent_id] => 20
)
[3] => Array
(
[label] => Child Level 1
[id] => 24
[parent_id] => 20
[items] => Array
(
[0] => Array
(
[label] => Child Level 2
[id] => 25
[parent_id] => 24
)
[1] => Array
(
[label] => Child Level 2
[id] => 26
[parent_id] => 24
)
)
)
)
)
)
现在我想让下面的数组显示在一个表中,每个子级缩进,如果它应该从子级3上升到子级2,索引应该再次反转
范例
<table border="2" width="100%">
<tr>
<td>Main Cat</td>
</tr>
<tr>
<td>Main Cat</td>
</tr>
<tr>
<td>Main Cat</td>
</tr>
<tr>
<td style="margin-left:20px;">Child Level 1</td>
</tr>
<tr>
<td style="margin-left:20px;">Child Level 1</td>
</tr>
<tr>
<td style="margin-left:40px;">Child Level 2</td>
</tr>
<tr>
<td style="margin-left:60px;">Child Level 3</td>
</tr>
<tr>
<td style="margin-left:20px;">Child Level 1</td>
</tr>
<tr>
<td style="margin-left:20px;">Child Level 1</td>
</tr>
<tr>
<td style="margin-left:40px;">Child Level 2</td>
</tr>
<tr>
<td style="margin-left:40px;">Child Level 2</td>
</tr>
</table>
变量$items包含上面的数组我注意到您自己的解决方案引用了变量$class,所以我也合并了它。您真的不需要使用CHtml(除非您这样做,但我从未见过这种情况)
函数renderItems($array,$class,$indent=0){
foreach($items作为$item){
回显'.$item['label'].';
if(设置($item['items')和计数($item['items'))
renderItems($item['items',$class,$indent+1);
}
}
为什么不使用JSON?这就是它的用途。这个问题与JSON无关……除非你想让他使用AJAX并用Javascript模板在客户端构建它。你确实应该使用嵌套列表来实现这一点,但我会在下面给出一个使用tabling的解决方案。@runspired-嵌套列表可以完成这项工作,但我需要将它放在一个选项卡中ular格式,带边框等,除非我可以设计列表的样式,使其外观和行为类似于表格,但我不确定它是否会在未来得到第二列。谢谢你的解决方案,实际上它真的很简单;-)我就快到了;-)无论如何,我使用了你的解决方案,效果很好。再一次,谢谢你,为我节省了很多时间
public function renderCategoriesRecursive($items)
{
foreach($items as $item)
{
$itemCount = count($item['items']);
echo CHtml::openTag('tr');
echo CHtml::openTag('td',array('class'=>$class));
echo $item['label'];
echo CHtml::closeTag('tr');
echo CHtml::closeTag('tr');
if(isset($item['items']) && $itemCount)
{
$this->renderCategoriesRecursive($item['items']);
}
}
}
function renderItems( $array, $class, $indent = 0 ) {
foreach( $items as $item) {
echo '<tr><td class="'.$class.'">'.$item['label'].'</td></tr>';
if( isset( $item['items'] && count( $item['items'] )
renderItems($item['items'],$class,$indent+1);
}
}