I need to separate a single array into sub arrays based on the amount of times > appears within the array key so that I tell who is a parent category and who isn't. Note that there is no limit to the amount of possible nested parents.
Also, if a child with the same name exists, it is considered unique if it has a different parent.
My source array structure looks like 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 with 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 the above example, Test Parent>Test Child>Test Sub Child would mean that there is a parent category Test Parent that has a child Test Child. Test Child also is a parent and has a child called Test Sub Child that does not have any children.
Example output required:
array (
'Collections' =>
array (
'Sports' => NULL,
'Charity' => NULL,
),
'Test Parent' =>
array (
'Test Child' =>
array (
'Test Sub Child' => NULL,
),
),
'Test Parent 2 with No kids' => NULL,
'Study' =>
array (
'Study Groups' => NULL,
),
)
I attempted a solution but can't manage to get the syntax right so that I can create an additional array with a child's children.
I don't necessarily require my example to be refactored. I am simply looking for the best solution that works.
My example code
$category_structure = array();
foreach($event_categories as $main_cat => $content_ids) {
$this_category_list = explode('>', $main_cat);
$this_cat = array();
$this_parent = array_shift($this_category_list);
foreach($this_category_list as $cat) {
$this_cat[$this_parent][$cat] = null;
}
$category_structure = array_merge_recursive($this_cat, $category_structure);
}
var_dump()of your array, consider posting avar_export()of it instead.