i got menus that are stored in a db like this
INSERT INTO `mycms_menus` (`menu_id`, `title`, `pos`, `parent_menu_id`) VALUES (1, 'Menu principal', 0, 0), (2, 'Menu secondaire', 0, 0), (3, 'SUBMENU 1-1', 0, 1), (4, 'SUBMENU 2-1', 0, 2), (5, 'SUBMENU 1-2', 0, 1), (6, 'SUBMENU 2-2', 0, 2), (7, 'submenu 2-3', 0, 2), (10, 'submenu 1-2-1', 0, 5);
i use a function to convert it to a nested array (multidim)
function _flat_to_nested($source) { $nodes = array(); $tree = array(); foreach ($source as &$node) { $node->children = array(); $id = $node->menu_id; $parent_id = $node->parent_menu_id; $nodes[$id] =& $node; if (array_key_exists($parent_id, $nodes)) { $nodes[$parent_id]->children[] =& $node; } else { $tree[] =& $node; } } return $tree; }
It returns a structured array like :
Array
(
[0] => stdClass Object
(
[menu_id] => 1
[title] => Menu principal
[pos] => 0
[parent_menu_id] => 0
[children] => Array
(
[0] => stdClass Object
(
[menu_id] => 3
[title] => SUBMENU 1-1
[pos] => 0
[parent_menu_id] => 1
[children] => Array
(
)
)
[1] => stdClass Object
(
[menu_id] => 5
[title] => SUBMENU 1-2
[pos] => 0
[parent_menu_id] => 1
[children] => Array
(
[0] => stdClass Object
(
[menu_id] => 10
[title] => submenu 1-2-1
[pos] => 0
[parent_menu_id] => 5
[children] => Array
(
)
)
)
)
)
)
[1] => stdClass Object
(
[menu_id] => 2
[title] => Menu secondaire
[pos] => 0
[parent_menu_id] => 0
[children] => Array
(
[0] => stdClass Object
(
[menu_id] => 4
[title] => SUBMENU 2-1
[pos] => 0
[parent_menu_id] => 2
[children] => Array
(
)
)
[1] => stdClass Object
(
[menu_id] => 6
[title] => SUBMENU 2-2
[pos] => 0
[parent_menu_id] => 2
[children] => Array
(
)
)
[2] => stdClass Object
(
[menu_id] => 7
[title] => submenu 2-3
[pos] => 0
[parent_menu_id] => 2
[children] => Array
(
)
)
)
)
)
3.but here i'm stuck because i need to convert this nested array to be used in form_dropdown from codeigniter html helper that requires a similar array but with a different structure like:
$options = array(
'menu_id' => 'menu title',
'##' => 'text',
'optgroup text' => array(
'menu_id' => 'menu title',
'##' => 'text',
),
),
);
echo form_dropdown('name',$options,null)
This will convert the nested array to a dropdown with nested optgroups.
i could'nt succeed in converting my table menu datas to a nested dropdown that i can use with the dropdown helper so i wish that someone could give me a tip or clues to achieve that. thanx in advance Im' aware that I might rewrite the whole process to do so, so any idea is welcome