Repository navigation
Collection::keyBy(), with multiple values/levels #61172
Replies: 2 comments
|
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 |
|
You can combine $result = $collection
->groupBy('first_key')
->map(fn ($group) => $group->keyBy('second_key'));
Dots in the values of either key are preserved literally, since this doesn't build a dotted path or call One difference from your Also, the first sample item has |
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