I have a MySQL table with a tree data structure. The fields are _id
, name
and parentId
. When the record hasn\'t a parent, parent
Hi Guys you could do something like this:
I have this object for the $tree
:
Array
(
[0] => stdClass Object
(
[id] => 1
[nombre] => Category 1
[subcategorias] => Array
(
[0] => stdClass Object
(
[id] => 4
[nombre] => Category 1.1
)
)
)
[1] => stdClass Object
(
[id] => 2
[nombre] => Category 2
)
[2] => stdClass Object
(
[id] => 3
[nombre] => Category 3
[subcategorias] => Array
(
[0] => stdClass Object
(
[id] => 5
[nombre] => Category 3.1
[subcategorias] => Array
(
[0] => stdClass Object
(
[id] => 6
[nombre] => Category 3.1.1
)
)
)
)
)
)
Then Here is how to create the array for the HTML select:
$tree=array();// PUT HERE YOUR TREE ARRAY
$arrayiter = new RecursiveArrayIterator($tree);
$iteriter = new RecursiveIteratorIterator($arrayiter);
$lista=array();
$i=0;
foreach ($iteriter as $key => $value)
{
$id=$iteriter->current();
$iteriter->next();
$nivel=$iteriter->getDepth();
$nombre=str_repeat('-',$nivel-1).$iteriter->current();
$lista[$id]=$nombre;
}
You will get something like this:
Array
(
[1] => Category 1
[4] => --Category 1.1
[2] => Category 2
[3] => Category 3
[5] => --Category 3.1
[6] => ----Category 3.1.1
)
Then you just need to create the options for the select with a simple foreach.
function toUL ($arr, $depth = 0) {
// ...
$html .= toUL($v['children'], $depth+1);