-
Notifications
You must be signed in to change notification settings - Fork 11.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
LazyCollection chunk using generator delegation #31761
Comments
@JosephSilber I guess this isn't possible with LazyCollections? |
This has nothing to do with lazy collections. You can see the same behavior using native generators: function generate($times = 1) {
yield 1;
yield 2;
yield 3;
if ($times > 1) {
yield from generate($times - 1);
}
}
iterator_to_array(generate(2)); The above will return The reason this happens is because every time you yield within a generator function without an explicit key, it actually yields a numerically indexed key/value pair. Every time you However, when you function generate() {
yield 0 => 1;
yield 1 => 2;
yield 2 => 3;
yield 0 => 1;
yield 1 => 2;
yield 2 => 3;
} When you later convert these to an array, the later indices overwrite the earlier ones. The solution is to call $collection->values()->chunk(4)->toArray(); // [[1, 2, 3, 1], [2, 3]] |
Hey @ankr, please see the answer above. @JosephSilber thanks! |
@JosephSilber Thank you for the thorough explanation! It all makes sense. |
Hi, I made a blog post explaining this here: https://not-a-number.io/2020/lazy-collection-oddities/ I saw this thread after when I started to share the link to the post, thanks @JosephSilber for that! |
Description:
When using generator delegation in combination with
LazyCollection::chunk()
and a chunk size greater than amount of values yielded from initial generator, all values from delegated generator are lost.Using a chunk smaller than (or equal to) the amount of values yielded from initial generator - everything works as expected.
Steps To Reproduce:
Make generator
Make collection
Chunk and inspect collection
The text was updated successfully, but these errors were encountered: