Created
November 17, 2016 13:43
-
-
Save nachodd/8cc62a67ae3304d1e1984b479b9ed239 to your computer and use it in GitHub Desktop.
Recursively walks a Collection or Array that contains children of the same kind and flatten into an single dimesion Collection or Array
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 | |
| // Recursively walks a Collection or Array that contains children of the same kind and flatten into an single dimesion Collection or Array. | |
| // Example: | |
| // We have: | |
| // A | |
| // |_B | |
| // |_C | |
| // |_D | |
| // We want: | |
| // A | |
| // B | |
| // C | |
| // D | |
| public static function childrenFlatArray($arr, &$acc=[]) { | |
| foreach($arr as $key => $item) { | |
| // if it have children | |
| if( count($item["children"]) > 0 ) { | |
| self::childrenFlatArray($item["children"], $acc); | |
| } | |
| // erase array in children | |
| unset($item["children"]); | |
| $acc[] = $item; | |
| } | |
| return $acc; | |
| } | |
| // Same, but with Laravel Collection (Illuminate\Support\Collection) | |
| public static function childrenFlatCollection($collection, &$acc) { | |
| $collection->each(function ($item, $key) use(&$acc) { | |
| if ( $item->children->count() > 0 ) { | |
| self::childrenFlatCollection($item->children, $acc); | |
| } | |
| // FIXME: Can not unset relations. =( | |
| $acc->prepend($item); | |
| }); | |
| return $acc; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment