doujia7094 2014-10-02 09:23
浏览 17

从MySQL制作树形结构

My table structure is as follows:

id | name | reporting_to
1  | AAA  | 0
2  | BBB  | 1
3  | CCC  | 2
4  | DDD  | 2
and so on...

i would like to print it so it generates as such

<ul>
<li> AAA
     <ul>
        <li>BBB
            <ul>
               <li>CCC</li>
               <li>DDD<li>
            </ul>
        </li>
      </ul>
</li>
</ul>

My current code works with one tiny catch:

function make_tree($parent, $array, $level = 0){
    if(!is_array($array) || empty($array)) return FALSE;

    $output = '<ul>';
    foreach($array as $index => $item)
    {
        if($item->reporting_to == $parent)
        {
            $output .= '<li>'.$item->name;
            $output .= $this->make_tree($item->id, $array, $level+1);
            $output .= '</li></li>';
        }
    }
    $output .= '</ul>';
    return $output;
}

The code above prints the following: // Notice how the <ul> gets printed on every last children.

<ul>
   <li>AAA
    <ul>
      <li>BBB
      <ul>
        <li>CCC</li>
        <ul></ul> // How do i get rid of this ?
        <li>DDD</li>
        <ul></ul> // This one too...
      </ul>
      </li>
    </ul>
    </li>
  </ul>

I am not sure how to remove the <ul> on every last child. Can anyone help me to structure the <ul>? Thanks.

EDIT:

I think the better question is:

Using my existing code, how should i identify whether given node is the last child (that particular node has no more children).

  • 写回答

1条回答 默认 最新

  • douqiang5809 2014-10-02 10:16
    关注

    You can do it later on, also remove from loop it seams to duplicated:

    function make_tree($parent, $array, $level = 0){
        if(!is_array($array) || empty($array)) return FALSE;
    
        $output = '<ul>';
        $hasChildren = false;
        foreach($array as $index => $item)
        {
            if($item->reporting_to == $parent)
            {
                $hasChildren = true;
                $output .= '<li>'.$item->name;
                $output .= $this->make_tree($item->id, $array, $level+1);
                $output .= '</li>';
            }
        }
        if(!$hasChildren){
            return '';
        }
        $output .= '</ul>';
        return $output;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题