Skip to content

Instantly share code, notes, and snippets.

@kagan94
Created May 8, 2017 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kagan94/48a28fda5d253d46c6e171366625970c to your computer and use it in GitHub Desktop.
Save kagan94/48a28fda5d253d46c6e171366625970c to your computer and use it in GitHub Desktop.
May be used to print nested category structure with parent_id, category_id attributes
function build_nested_array($records){
/* Build nested array on the menu example */
$menu = array();
$menu_index = array();
foreach ($records as $record){
if($record['parent_id'] == 0) {
$menu[] = [
'name' => $record->name,
'child' => []
];
$menu_index[$record->id] = &$menu[sizeof($menu)-1];
} else {
$menu_index[$record->parent_id]['child'][] = [
'name' => $record->name
];
$menu_index[$record->id] = &$menu_index[$record->parent_id]['child'][sizeof($menu_index[$record->parent_id]['child'])-1];
}
}
return $menu;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment