我在以下场景中遇到了困难,我有一个包含类别的数组,因此类别可以有子类别,而子类别可以有无限的子类别。现在我想要实现的是以下目标,但我无法实现这一目标。
$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
)
)
)
)
)
)
现在我希望下面的数组显示在一个表格中,每个子级别都缩进,如果它应该从 Child Level 3 上升到 Child Level 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>
到目前为止,我的 PHP 代码看起来像这样,
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']);
}
}
}
变量$items包含上面的数组