Jeremy
Jeremy

Reputation: 2536

Making Tree Structure from 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).

Upvotes: 0

Views: 152

Answers (1)

Michał Fraś
Michał Fraś

Reputation: 407

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

Upvotes: 1

Related Questions