NotionCommotion Posted April 19, 2023 Share Posted April 19, 2023 The following works, but seems like it has one more loop than it should. Better way to do so? I could get rid of the generator and merge to an array, but the generator seems like a better solution. Thanks private function doSomething(File $file) { foreach($this->getTextFiles($file) as $textFile) { // ... } } private function getTextFiles(File $file):\Generator { foreach($file->getChildren() as $child) { if($child instanceof IsTextFile) { yield $child; } else { foreach($this->getTextFiles($child) as $grandChild) { yield $grandChild; } } } } Quote Link to comment https://forums.phpfreaks.com/topic/316162-recursive-generator/ Share on other sites More sharing options...
Solution requinix Posted April 19, 2023 Solution Share Posted April 19, 2023 You can "yield from" another generator. private function getTextFiles(File $file):\Generator { foreach($file->getChildren() as $child) { if($child instanceof IsTextFile) { yield $child; } else { yield from $this->getTextFiles($child); } } } 1 Quote Link to comment https://forums.phpfreaks.com/topic/316162-recursive-generator/#findComment-1607494 Share on other sites More sharing options...
NotionCommotion Posted April 19, 2023 Author Share Posted April 19, 2023 Thanks, exactly what I was hoping for! Tried without the "from" but obviously didn't do what I wished for. Quote Link to comment https://forums.phpfreaks.com/topic/316162-recursive-generator/#findComment-1607495 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.