-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
[5.4] mapWithKeys shouldn't reindex the collection #16552
Conversation
I definitely don't want to be passing a |
This might be fixable by avoiding collapse and using a simple loop, though there may be more optimal solutions. Also take care of preserving the array order (not the same as the numerical indexes). To verify this, a foreach on the result should iterates the items in the same order. |
Here is what I have currently: collect()->macro('mapWithKeys_v2', function ($callback) {
$result = [];
foreach ($this->items as $key => $value) {
$assoc = $callback($value, $key);
$mapValue = reset($assoc);
$mapKey = key($assoc);
$result[$mapKey] = $mapValue;
}
return new static($result);
}); |
@vlakoff I'm simplifying it a little bit i'll create a PR. |
I don't know if the callback returning several rows is a supported use case, but it could be useful and maybe some people do it, and more importantly to preserve BC: foreach ($this->items as $key => $value) {
$assoc = $callback($value, $key);
foreach ($assoc as $mapKey => $mapValue) {
$result[$mapKey] = $mapValue;
}
} |
Refs subsequent PR by fernandobandeira: #16564 |
I think If there are non-consecutive numeric keys, it's because the user has specified them. So the user probably expects them to be retained… |
Makes sense, currently $collection = collect([
[1 => 'Sally'],
[3 => 'Arkansas'],
[2 => 28]
]);
$flattened = $collection->flatMap_v2(function ($values) {
return array_map('strtoupper', $values);
}); results into: [
0 => "SALLY",
1 => "ARKANSAS",
2 => "28"
] Is this intended? If it isn't then we could change flatMap and just alias mapWithKeys since it's just another syntax for the callback as it is currently, and add a test to flatMap... |
agree. |
Mmmm, wait. $collection = collect([
['Sally'],
['Arkansas'],
[28]
]);
$callback = function ($values) {
return array_map('strtoupper', $values);
};
print_r( $collection->flatMap($callback)->all() );
print_r( $collection->mapWithKeys_v2($callback)->all() ); Results:
Let's not touch |
mapWithKeys
shouldn't reindex the array when using numeric keys, added a flag to change this behavior and the tests accordingly.Refs: #15409, #16142
This was a predicted behavior: #14430 (comment) but since people are using it for this purpose and the name is kinda misleading i thought we should address this...
Update: If this should be the intended behavior then we could add a note to the docs about it...