I'm basically trying to build an html ul/li nested list from a multidimensional array representing a tree structure.
The following code works fine but I want to improve it:
I need a way to keep track of the recursion level so I can apply different classes to different levels, add indenting to the generated output, etc.
function buildTree($tree_array, $display_field, $children_field, $class='', $id='') {
echo "<ul>\n";
foreach ($tree_array as $row) {
echo "<li>\n";
echo $row[$display_field] . "\n";
if (isset($row[$children_field])) {
$this->buildTree($row[$children_field]);
}
echo "</li>\n";
}
echo "</ul>\n";
}
The $tree_array looks like this:
Array
(
[0] => Array
(
[category_id] => 1
[category_name] => calculatoare
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[category_id] => 4
[category_name] => placi de baza
[parent_id] => 1
)
[1] => Array
(
[category_id] => 5
[category_name] => carcase
[parent_id] => 1
[children] => Array
(
[0] => Array
(
[category_id] => 6
[category_name] => midi-tower
[parent_id] => 5
)
)
)
)
)
[1] => Array
(
[category_id] => 2
[category_name] => electronice
[parent_id] => 0
)
[2] => Array
(
[category_id] => 3
[category_name] => carti
[parent_id] => 0
)
)
I've tagged this as homework because I'd like to use this as an opportunity to improve on my (poor) understanding of recursion so, I'd appreciate answers that would guide me to the solution rather than provide a complete working example :)