2015-01-15 54 views
2

我有以下的数组:生成基于在阵列上嵌套的HTML代码

[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>'; 
    } 
} 

我完全不知道这是怎么回事。

+0

你能提供给我你的数组中的PHP做一些测试? – 2015-01-15 20:21:52

回答

0

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); 

?>