The current implementation is the following
/**
* Run a filter over each of the items.
*
* @param Closure $callback
* @return \Illuminate\Support\Collection
*/
public function filter(Closure $callback)
{
return new static(array_filter($this->items, $callback));
}
array_map
has the side effect that it will keep the array keys as they were originally
As a result, when json-i-fying the filtered result, the result will not be a simple array, but an object with key=>value pairs.
For example:
{"4": {"name": "Koen"}, "7": {"name": "Taylor"}}
VS
[{"name": "Koen"}, {"name": "Taylor"}]
I suggest we change the filter method into this:
/**
* Run a filter over each of the items.
*
* @param Closure $callback
* @return \Illuminate\Support\Collection
*/
public function filter(Closure $callback)
{
return new static(array_values(array_filter($this->items, $callback)));
}
Which will clean up the keys, and turn everything back to normal.
I would just run values
on the Collection. Some might expect array_filter on a collection to preserve arrays like it normally would.
This might solve the problem @vespakoen mentioned:
$collection = collect($collection->values());
It takes out the values, and then make it a collection again.
This might solve the problem @vespakoen mentioned:
$collection = collect($collection->values());
It takes out the values, and then make it a collection again.
You save my day, man :P
This might solve the problem @vespakoen mentioned:
$collection = collect($collection->values());
It takes out the values, and then make it a collection again.
Laravel 5 and later returns a new Collection
instance when running values
. Because of that, running collect
should _not_ be necessary. Resulting in;
$valuesCollection = $collection->values();
Most helpful comment
I would just run
values
on the Collection. Some might expect array_filter on a collection to preserve arrays like it normally would.