Collection::keyBy(), with multiple values/levels #61172
Unanswered
jay-knight
asked this question in
Ideas
Replies: 1 comment
|
I'll answer my own question with something that works, but I don't really like (with some help from Claude): collect($collection
->reduce(function ($carry, $item) {
data_set($carry, [$item['first_key'], $item['second_key']], $item, false);
return $carry;
}, []));This "reduces" the collection into an array that looks the way I want, then wraps the whole thing into a |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I have a need to be able to take a collection and "key" it by multiple values. Consider:
In this collection, I know that the combination of
firstandsecondwill always be unique. So I'd like to arrange this like:$collection->groupBy(["first_key", "second_key"]])gets me really close, but there is a third level of collections, each with one array:It would be really nice if
$collection->keyBy(["first_key", "second_key"]])would behave similarly, but keep the value of the second level one of the original arrays instead of an array containing that original array.So:
I did try to
And that comes really close, but if either of the key values contain a dot (which they can), it messes that up and adds a third level.
All reactions