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>