php - Is it possible to group this array? -


i have array , need sort array in multilevel array. i'm trying group fields can make work. here example of array have , want

array ( [0] => array ( [id] => sports [title] => sports ) [1] => array ( [id] => cricket [title] => cricket [under] => sports ) [2] => array ( [id] => batsman [title] => batsman [under] => cricket ) [3] => array ( [id] => sachin [title] => sachin [under] => batsman ) [4] => array ( [id] => football [title] => football [under] => sports ) [5] => array ( [id] => ronaldo [title] => ronaldo [under] => football ) ) 

i need group array , make

array( [0] => array( [id] => array( [sports] => array( [cricket] => array( [batsman] => sachin ) [football] => fun ) ) ) ) 

i tried not working

foreach($my_array $item) { //group them under $my_grouped_array[$item['under']][] = $item; } 

any suggestion great.

i think straight-forward way of doing this:

function getchildren($entry,$by_parent){ $children = array(); if (isset($by_parent[$entry['id']])){ foreach ($by_parent[$entry['id']] $child){ $id = $child['id']; $children[$id] = getchildren($child,$by_parent); } } return $children; } $by_parent = array(); $roots = array(); foreach ($array $entry){ if (isset($entry['under'])){ $by_parent[$entry['under']][] = $entry; } else { $roots[] = $entry; } } $result = array(); foreach ($roots $entry){ $id = $entry['id']; $result[$id] = getchildren($entry,$by_parent); } $results = array(array('id'=>$results)); 

note: isn't quite format specified in question, question doesn't define how deal multiple leaf nodes same parent, , should easier traverse anyway, because it's more consistent.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -