Created
September 19, 2016 08:38
-
-
Save petrkotek/d4cb2350edf181f29c9219613a25c01e to your computer and use it in GitHub Desktop.
Demonstrates how to implement recursive generators in PHP 7.0+
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)) { | |
yield from walkTree($value, $depth + 1); | |
} | |
} | |
} | |
$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 | |
*/ |
Hi @dino9g, if I recall correctly, I used this approach because the input size was big and iterator_to_array
would use way too much memory.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, it seems that generators and recursion don't mix! Indeed, did you try to do an iterator_to_array? You will be surprised!