Last active
September 19, 2016 08:44
-
-
Save petrkotek/90137df6abb20d3030770c8401ec00c7 to your computer and use it in GitHub Desktop.
Demonstrates how to implement recursive generators in PHP 5.5+
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 | |
| function walkTree($tree, $depth = 0) { | |
| foreach ($tree as $key => $value) { | |
| yield ['depth' => $depth, 'name' => $key]; | |
| if (is_array($value)) { | |
| foreach (walkTree($value, $depth + 1) as $yeilded) { | |
| yield $yeilded; | |
| } | |
| } | |
| } | |
| } | |
| $tree = [ | |
| 'fruit' => [ | |
| 'apple' => [ | |
| 'granny smith' => null, | |
| ], | |
| 'pear' => null, | |
| ], | |
| 'vegatable' => [ | |
| 'avocado' => null, | |
| 'tomato' => null, | |
| 'potato' => null, | |
| ], | |
| 'meat' => [ | |
| 'chicken' => null, | |
| 'pork' => null, | |
| 'beef' => null, | |
| 'kangaroo' => null, | |
| ], | |
| ]; | |
| // echo '<pre>' . PHP_EOL; | |
| foreach (walkTree($tree) as $node) { | |
| echo str_repeat(' ', $node['depth']) . '- ' . $node['name'] . PHP_EOL; | |
| } | |
| // echo '</pre>' . PHP_EOL; | |
| /* | |
| OUTPUT: | |
| - fruit | |
| - apple | |
| - granny smith | |
| - pear | |
| - vegatable | |
| - avocado | |
| - tomato | |
| - potato | |
| - meat | |
| - chicken | |
| - pork | |
| - beef | |
| - kangaroo | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment