If I've understood right you only need to get rid of the <ul>...</ul> wrapping the initial function call and modify the if-statement inside the function just a little bit to let it proceed on the first round even if there are no records found. Like this:
<?php
function listProducts($productCat,$level=0) {
$result = wire('db')->query("SELECT id, product, productcat FROM products WHERE productcat='$productCat' ORDER BY subcat");
if($level > 0 && $result->num_rows == 0) return;
echo "<ul class='sortable'>\n";
while (list ($id, $product) = $result->fetch_row()) {
echo "<li id='item_{$id}'>\n";
echo "<div class='dd-handle'>{$product}</div>\n";
listProducts($id,$level+1);
echo "</li>\n";
}
echo "</ul>\n";
}
?>
<div>
<h5>Products</h5>
<?php echo listProducts(0);//call the function ?>
</div>
As a side note, I usually build a simple safety net when using recursive functions just to be on the safe side if (when) there's suddenly broken data in the database. Here that would mean adding one line at the beginning of the function:
// ~25 levels of product categories could be considered an error, I think.
// Use something big enough to allow any legitimate data but small enough to allow the server stay alive.
if($limit > 25) throw new WireException("Recursion gone wild");
While it's not necessary, it's a small price to pay for peace of mind
.





Find content
Male

