PHP类树递归

时间:2012-02-28 23:11:38

标签: php html arrays recursion tree

我需要通过数组递归来构建类别表。只要深度变深,它就可以正常工作,但只要深度减小,HTML输出就会错过表格的开头。

构建数组的PHP代码:

       if($query->rowCount() > 0) {
        while($result = $query->fetch(PDO::FETCH_OBJ)) {
            $tree[] = $result;
        }
        $childs = array();

        foreach($tree as $item) {
            $childs[$item->parent_id][] = $item;
        }


        foreach($tree as $item) {
            if (isset($childs[$item->id])) {
               $item->childs = $childs[$item->id];
            }
        }

        $tree = $childs[0];
    }
    else {
        // no category blabla
    }

这是构建表的功能。它无法正常工作。

    function draw($tree) {
    echo "<table border='1' width='300'>";
    echo "<tr>";
    echo "<td>Name</td><td>Depth</td><td>Parent</td>";
    echo "</tr>";
    foreach($tree as $key => $value) {
        echo "<tr>";
        echo "<td>".$value->name."</td>";
        echo "<td>".$value->depth."</td>";
        echo "<td>".$value->parent_id."</td>";
        echo "</tr>";
        if(isset($value->childs)) {
            draw($value->childs);
        }
    }
    echo "</table>";

}

根据要求提供HTML输出代码段:

<table border='1' width='300'>
    <tr>
        <td>Name</td>
        <td>Depth</td>
        <td>Parent</td>
    </tr>
    <tr>
        <td>Bad</td>
        <td>5</td>
        <td>5</td>
    </tr>
    <tr>
        <td>Good</td>
        <td>5</td>
        <td>5</td>
    </tr>
</table>
    <!--- BREAK HAPPENS HERE----->
    <tr>
        <td>Both?</td>
        <td>4</td>
        <td>3</td>
    </tr>
    <table border='1' width='300'>
        <tr>
            <td>Name</td>
            <td>Depth</td>
            <td>Parent</td>
        </tr>
        <tr>
            <td>dsadas</td>
            <td>5</td>
            <td>16</td>
        </tr>
    </table>

2 个答案:

答案 0 :(得分:2)

<击> 这样做:

    echo "<tr><td colspan='3'>";
    if(isset($value->childs)) {
        draw($value->childs);
    }
    echo "</td></tr>"

<击>

请改为:

    if(isset($value->childs)) {
        echo "<tr><td colspan='3'>";
        draw($value->childs);
        echo "</td></tr>"
    }

您正在表的正文中创建一个新表。那是无效的HTML。你必须将它放在自己的TD中。

答案 1 :(得分:0)

  function draw($tree) {
    if(!$tree) return;
    $nextLevel = array();
    echo "<table border='1' width='300'>";
    echo "<tr>";
    echo "<td>Name</td><td>Depth</td><td>Parent</td>";
    echo "</tr>";
    foreach($tree as $key => $value) {
        echo "<tr>";
        echo "<td>".$value->name."</td>";
        echo "<td>".$value->depth."</td>";
        echo "<td>".$value->parent_id."</td>";
        echo "</tr>";
        if(isset($value->childs) && $value->childs){
           $nextLevel = array_merge($nextLevel, $value->childs);
        }
    }
    echo "</table>";
    draw($nextLeveL);
}