根据数组生成嵌套的HTML代码

时间:2015-01-15 18:29:16

标签: php arrays

我有以下数组:

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

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

1 个答案:

答案 0 :(得分: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);

?>