Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP category tree recursion

I need to build a table of categories by recursion through an array. It works fine as long as the depth goes deeper but as soon as the depth decreases the HTML output misses the start of a table.

PHP code to build the array:

       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
    }

Here is the function to build the table. It fails to work correctly.

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

}

As requested the HTML Output snippet:

<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>
like image 581
Sepix Avatar asked May 23 '26 16:05

Sepix


1 Answers

do this:

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

Do this instead:

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

You are creating a new table within the body of a table. That is invalid HTML. You have to put it in its own TD.

like image 138
Daan Timmer Avatar answered May 26 '26 08:05

Daan Timmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!