Skip to content

Conversation

@jasonmccreary
Copy link
Contributor

I had the need to collapse a collection of nested arrays while preserving their keys. Neither the flatten nor collapse methods have a flag for preserving keys. While it may not for flatten, the option may make sense for collapse given its single depth.

Consider the following collection (before/after):

[[1 => 'a'], [3 => 'c'], [2 => 'b']] // before
[1 => 'a', 3 => 'c', 2 => 'b']       // after

Of course, you may achieve the after result using mapWithKeys and a custom callback or some pipeline of collection methods. But this seems like a common enough use case for a collapseWithKeys (or better name) to exist.

@jasonmccreary
Copy link
Contributor Author

Note, I didn't add this method to Arr or Eloquent\Collection. I don't see a use case for Eloquent\Collection, and didn't know the level of method symmetry between the Arr and Collection classes.

@taylorotwell taylorotwell merged commit c917b0e into laravel:11.x Aug 1, 2024
@jasonmccreary jasonmccreary deleted the collapse-with-keys branch August 1, 2024 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants