$cat['id'], 'name' => $cat['name'], 'level' => 1, 'children' => array(), ); } else { $child = array( 'id' => $cat['id'], 'name' => $cat['name'], 'level' => $level, ); if (empty($groups)) { $ungrouped[] = $child; } else { $groups[count($groups) - 1]['children'][] = $child; } } } return array('ungrouped' => $ungrouped, 'groups' => $groups); } }