Last active
August 29, 2015 14:26
-
-
Save amberlex78/6db35d46eea62a74f80f to your computer and use it in GitHub Desktop.
Tree::flat2nested($arr);
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| ----------------------------------- | |
| Reformat flat array to nested array | |
| ----------------------------------- | |
| Array( | |
| [2] => Array( | |
| [id] => 2 | |
| [parent_id] => 0 | |
| [title] => Новости | |
| ) | |
| [27] => Array( | |
| [id] => 27 | |
| [parent_id] => 2 | |
| [title] => www-1 | |
| ) | |
| [28] => Array( | |
| [id] => 28 | |
| [parent_id] => 2 | |
| [title] => www-2 | |
| ) | |
| [3] => Array( | |
| [id] => 3 | |
| [parent_id] => 0 | |
| [title] => Статьи | |
| ) | |
| [29] => Array( | |
| [id] => 29 | |
| [parent_id] => 3 | |
| [title] => www-3 | |
| ) | |
| ) | |
| Array( | |
| [2] => Array( | |
| [id] => 2 | |
| [parent_id] => 0 | |
| [title] => Новости | |
| [sub] => Array( | |
| [27] => Array( | |
| [id] => 27 | |
| [parent_id] => 2 | |
| [title] => www-1 | |
| ) | |
| [28] => Array( | |
| [id] => 28 | |
| [parent_id] => 2 | |
| [title] => www-2 | |
| ) | |
| ) | |
| ) | |
| [3] => Array( | |
| [id] => 3 | |
| [parent_id] => 0 | |
| [title] => Статьи | |
| [sub] => Array( | |
| [29] => Array( | |
| [id] => 29 | |
| [parent_id] => 3 | |
| [title] => www-3 | |
| ) | |
| ) | |
| ) | |
| ) | |
| */ | |
| /** | |
| * Class Tree | |
| */ | |
| class Tree | |
| { | |
| /** | |
| * Return nested array | |
| * @param array $arr_assoc | |
| * @return array | |
| */ | |
| public static function flat2nested(array $arr_assoc) | |
| { | |
| $nested_array = []; | |
| foreach ($arr_assoc as $id => &$node) { | |
| if (isset($node['parent_id'])) { | |
| if ($node['parent_id'] == 0) { | |
| $nested_array[$id] = &$node; | |
| } else { | |
| $arr_assoc[$node['parent_id']]['sub'][$id] = &$node; | |
| } | |
| } | |
| } | |
| return $nested_array; | |
| } | |
| } | |
| // Usage | |
| // | |
| Tree::flat2nested($arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment