php - Create seperate sub array based on array key -
i need separate single array sub arrays based on amount of times >
appears within array key tell parent category , isn't. note there no limit amount of possible nested parents.
also, if child same name exists, considered unique if has different parent.
my source array structure looks this:
array ( 'test parent 2>test child>test sub child' => array ( 'content_id_4' => null, ), 'test parent 3' => array ( 'content_id_4' => null, 'content_id_5' => null, ), 'test parent>test child>test sub child' => array ( 'content_id_3' => null, ), 'test parent 2 no kids' => array ( 'content_id_3' => null, ), 'collections>sports' => array ( 'content_id_2' => null, 'content_id_22' => null, ), 'collections' => array ( 'content_id_2' => null, 'content_id_22' => null, 'content_id_6' => null, ), 'collections>charity' => array ( 'content_id_6' => null, ), )
in above example, test parent>test child>test sub child
mean there parent category test parent
has child test child
. test child
parent , has child called test sub child
not have children.
example output required:
array ( 'collections' => array ( 'sports' => null, 'charity' => null, ), 'test parent' => array ( 'test child' => array ( 'test sub child' => null, ), ), 'test parent 2 no kids' => null, 'study' => array ( 'study groups' => null, ), )
i attempted solution can't manage syntax right can create additional array child's children.
i don't require example refactored. looking best solution works.
my example code
$category_structure = array(); foreach($event_categories $main_cat => $content_ids) { $this_category_list = explode('>', $main_cat); $this_cat = array(); $this_parent = array_shift($this_category_list); foreach($this_category_list $cat) { $this_cat[$this_parent][$cat] = null; } $category_structure = array_merge_recursive($this_cat, $category_structure); }
this should work you, making sure there no 0 indexed items in result. comes array_merge_recursive
think, merging null valued item ones have associative key.
it not elegant p0rnflake's solution though, sure idea.
$collect = array(); $result = array(); $last = ""; foreach($event_categories $main_cat => $content_ids) { if (strpos($last, $main_cat) === false) { array_push($collect, explode('>', $main_cat)); } $last = $main_cat; } array_walk($collect, function($value) use (&$result) { $out = array(); $cur = &$out; foreach ($value $array) { if (count($value) !== 1) { $cur[$array] = array(); } else { $cur[$array] = null; } $cur = &$cur[$array]; } $cur = null; $result = array_merge_recursive($result, $out); }); var_dump($result);
Comments
Post a Comment