8000 [8.x] Pass $key to closure in Collection and LazyCollection's reduce method as well by mokhosh · Pull Request #35878 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[8.x] Pass $key to closure in Collection and LazyCollection's reduce method as well #35878

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

Merged
merged 11 commits into from
Jan 15, 2021
Next Next commit
add reduce with keys to collections
  • Loading branch information
mokhosh committed Jan 10, 2021
commit 31dbc46a75d18bdccc6183994e68f1cbd90953ca
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,24 @@ public function reduce(callable $callback, $initial = null)
return array_reduce($this->items, $callback, $initial);
}

/**
* Reduce an associative collection to a single value.
*
* @param callable $callback
* @param mixed $initial
* @return mixed
*/
public function reduceWithKeys(callable $callback, $initial = null)
{
$result = $initial;

foreach($this->items as $key => $value) {
$result = $callback($result, $value, $key);
}

return $result;
}

/**
* Replace the collection items with the given items.
*
Expand Down
0