I have a MySQL table with a tree data structure. Fields _id, nameand parentId. When a record does not have a parent, it parentIdis used as 0 by default. This way I can build an array and then print each record recursively.
The built-in array is as follows:
Array
(
[1] => Array
(
[parentId] => 0
[name] => Countries
[_id] => 1
[children] => Array
(
[2] => Array
(
[parentId] => 1
[name] => America
[_id] => 2
[children] => Array
(
[3] => Array
(
[parentId] => 2
[name] => Canada
[_id] => 3
[children] => Array
(
[4] => Array
(
[parentId] => 3
[name] => Ottawa
[_id] => 4
)
)
)
)
)
[5] => Array
(
[parentId] => 1
[name] => Asia
[_id] => 5
)
[6] => Array
(
[parentId] => 1
[name] => Europe
[_id] => 6
[children] => Array
(
[7] => Array
(
[parentId] => 6
[name] => Italy
[_id] => 7
)
[11] => Array
(
[parentId] => 6
[name] => Germany
[_id] => 11
)
[12] => Array
(
[parentId] => 6
[name] => France
[_id] => 12
)
)
)
[8] => Array
(
[parentId] => 1
[name] => Oceania
[_id] => 8
)
)
)
)
Printing an unordered list is <ul>very easy with recursion. Here is the function I'm using:
function toUL ($arr) {
$html = '<ul>' . PHP_EOL;
foreach ( $arr as $v ) {
$html.= '<li>' . $v['name'] . '</li>' . PHP_EOL;
if ( array_key_exists('children', $v) ) {
$html.= toUL($v['children']);
}
}
$html.= '</ul>' . PHP_EOL;
return $html;
}
But I'm stuck when printing in a <select>tree-like way:
Countries
-- America
-- Asia
-- Europe
-- Oceania
I thought to print --as many times as the depth of an element, but I don’t know how to calculate the depth.
My question is: is it possible to build <select>without knowing depth?
Thanks in advance.