Skip to content

Instantly share code, notes, and snippets.

@petrkotek
Created September 19, 2016 08:38
Show Gist options
  • Save petrkotek/d4cb2350edf181f29c9219613a25c01e to your computer and use it in GitHub Desktop.
Save petrkotek/d4cb2350edf181f29c9219613a25c01e to your computer and use it in GitHub Desktop.
Demonstrates how to implement recursive generators in PHP 7.0+
<?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
*/
@dino9g
Copy link

dino9g commented Oct 17, 2020

Hello, it seems that generators and recursion don't mix! Indeed, did you try to do an iterator_to_array? You will be surprised!

@petrkotek
Copy link
Author

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