[英]Generate nested HTML code based on the array
我有以下数组:
[0] => [
'parent_id' => null,
'id' => 1,
'count' => 0
'children' => [
[0] => [
'parent_id' => 1,
'id' => 11,
'count' => count11
]
[0] => [
'parent_id' => 1,
'id' => 12,
'count' => count12
]
]
],
[1] => [
'parent_id' => null,
'id' => 2,
'count' => 0,
'children' => [
[0] => [
'parent_id' => 2,
'id' => 21,
'count' => 0,
'children' => [
[0] => [
'parent_id' => 21,
'id' => 211,
'count' => count211
]
]
]
]
]
而且我必须根据以下模式从中创建一个嵌套的HTML列表:
<ul>
<li><span>All categories (count)</span>
<ul>
<li>
<span>Category 1 (count1)</span>
<ul>
<li>
<span>Category 11 (count11)</span>
</li>
<li>
<span>Category 12 (count12)</span>
</li>
</ul>
</li>
<li>
<span>Category 2 (count2)</span>
<ul>
<li>
<span>Category 21 (count21)</span>
<ul>
<li>
<span>Category 211 (count211)</span>
</li>
</ul>
</li>
</ul>
</li>
</li>
</ul>
问题是,计数值仅存在于叶子中,因此父母将必须对孩子的所有值求和。 另一个问题是我在这里需要一个标头(所有类别),但是它在数组中不存在。
我怎样才能做到这一点?
我一直在尝试提出一些解决方案,但是没有一个可行。
public function generateHTML($arr, $html, $depth = 0)
{
if($depth == 0)
{
$html = '<ul><li><span>All categories</span></li>';
}
foreach($arr as $key => $value)
{
$html .= '<ul><li>';
$this->generateHTML($arr, $html, $depth++);
$html .= '</li></ul>';
}
if($depth == 0)
{
$html = '</ul>';
}
}
我完全不知道这看起来如何。
Blockquote这是根据您的要求的确切工作代码。
<?php
class test{
public function getTree($arr){
$html = '<ul>';
foreach($arr as $k=>$v){
$html .= '<li><span>'.$v['count'].'</span>';
if(isset($v['children'])){
if(is_array($v['children'])){
$html .= $this->getTree($v['children']);
}
}
$html .= '</li>';
}
return $html .= '</ul>';
}
}
$arr = array(
array(
'parent_id' => null,
'id' => 1,
'count' => 'count1',
'children' => array(
array(
'parent_id' => 1,
'id' => 11,
'count' => 'count11'
),
array(
'parent_id' => 1,
'id' => 12,
'count' => 'count12'
)
)
),
array(
'parent_id' => null,
'id' => 2,
'count' => 'count2',
'children' => array(
array(
'parent_id' => 1,
'id' => 21,
'count' => 'count21',
'children' => array(
array(
'parent_id' => 21,
'id' => 211,
'count' => 'count211'
)
)
)
)
)
);
$obj = new test();
echo $obj->getTree($arr);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.