Syafrizal Natawiria Syafrizal Natawiria - 4 years ago 86
PHP Question

Array grouping php into sub array

I have an array like this:

$array = array(
array('menu' => 'Menu Parent 1', 'link' => '#'),
array('menu' => 'Sub Menu Parent 1', 'link' => '/submenu1'),
array('menu' => 'Menu Parent 2', 'link' => '#'),
array('menu' => 'Sub Menu Parent 2.1', 'link' => '/submenu21'),
array('menu' => 'Sub Menu Parent 2.2', 'link' => '/submenu22'));


How can I turn it into the following array?

$array = array(
array('menu' => 'Menu Parent 1', 'link' => '#',
'submenu' => array(array('menu' => 'Sub Menu Parent 1', 'link' => '/submenu1'))
),
array('menu' => 'Menu Parent 2', 'link' => '#',
'submenu' => array(array('menu' => 'Sub Menu Parent 2.1', 'link' => '/submenu21'),
array('menu' => 'Sub Menu Parent 2.2', 'link' => '/submenu22'))
)
);

Answer Source

You can use array_reduce() using a custom aggregate function and a new array() as initial value.

Or iterate over the list looking for guess the parents from the menu text: in your case may be complicated because the parent wire is not explicit as element attribute.

Similar question: create array tree from array list

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download