I am struggling with an array I want to turn into a nested < select >
I need:
<select>
<option value="1">Top1</option>
<option value="2">Top2</option>
<option value="9">Top3</option>
<option value="7"> - - Top3.1</option>
<option value="5"> - - Top3.2</option>
<option value="12">- - - - Top3.2.1</option>
<option value="6">Top4</option>
<option value="4">Top5</option>
<option value="8"> - - Top5.1</option>
<option value="3"> - - Top5.2</option>
I can't work with optgroup, because everything is selectable. As far as I know, you can't select optgroup labels.
My array looks like this:
[44] => Array
(
[id] => 1
[name] => Test
[slug] => test
[parent] => 0
)
[45] => Array
(
[id] => 2
[name] => Test-Sub
[slug] => test-sub
[parent] => 1
)
[46] => Array
(
[id] => 3
[name] => Test-Sub-Sub
[slug] => test-sub-sub
[parent] => 2
)
I am feeling like I have tried dozens of variantions, but I can't build my form select right.
That was my last try:
function toDropdown($arr)
{
foreach ($arr as $row) {
$cat[$row['id']] = $row['name'];
if ($row['parent'] != 0) {
$cat[$row['id']] = '--' . $row['name'];
}
}
return $cat;
}
But this way, it is ordered by the ID and the nesting loses its meaning.
I'll try to go on, but if someone can help I appreciate any help!
EDIT: PHP Data
My function to get all categories from the DB:
function get_categories($parent = 'all')
{
$this->db->select('categories.id, categories.name, categories.slug, categories.parent');
$this->db->from('categories');
if ($query = $this->db->get())
{
return $query->result_array();
}
return FALSE;
}
My view.php, where I output all data:
$query = $this->datei_model->get_categories('all');
foreach ($query as $row)
{
$parents[] = $row;
}
$tree = buildTree($parents);
print("<select>\n");
printTree($tree);
print("</select>");
Try this;
Output;
And in your case;
In Qeremy's code just change this line and the code will not be giving you any incrementing dashes
to ->
this just litle change of the original code that answered by Qeremy
Now the dashed name works great. *sorry for my english