I have an array and I need to sort this array in a multilevel array. I’m trying to group it by its fields but I can make it work. Here is the example of the array I have and what I want
Array
(
[0] => Array
(
[id] => sports
[title] => this is sports
)
[1] => Array
(
[id] => cricket
[title] => this is cricket
[under] => sports
)
[2] => Array
(
[id] => batsman
[title] => this is batsman
[under] => cricket
)
[3] => Array
(
[id] => sachin
[title] => this is sachin
[under] => batsman
)
[4] => Array
(
[id] => football
[title] => this is football
[under] => sports
)
[5] => Array
(
[id] => ronaldo
[title] => this is ronaldo
[under] => football
)
)
I need to group this array and make it like this
Array(
[0] => Array(
[id] => Array(
[sports] => Array(
[cricket] => Array(
[batsman] => sachin
)
[football] => fun
)
)
)
)
I tried something like this but it is not working
foreach($my_array as $item) {
//group them by under
$my_grouped_array[$item['under']][] = $item;
}
Any suggestion will be great.
I think this is the most straight-forward way of doing this:
NOTE: This isn’t quite the format specified in the question, but the question doesn’t define how to deal with multiple leaf nodes with the same parent, and this should be easier to traverse anyway, because it’s more consistent.