Skip to content

Instantly share code, notes, and snippets.

@petrkotek
Last active September 19, 2016 08:44
Show Gist options
  • Select an option

  • Save petrkotek/90137df6abb20d3030770c8401ec00c7 to your computer and use it in GitHub Desktop.

Select an option

Save petrkotek/90137df6abb20d3030770c8401ec00c7 to your computer and use it in GitHub Desktop.
Demonstrates how to implement recursive generators in PHP 5.5+
<?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