为什么在这种情况下 Laravel Collection 上的 `reject()` 方法会返回一个关联数组?

eys*_*kal 1 php laravel

为什么要将reject()这个集合中的项目转换为关联数组?

>>> collect([1, 2, 'X', 4])->reject('X')->all();
=> [
     0 => 1,
     1 => 2,
     3 => 3,
   ]
>>> 
Run Code Online (Sandbox Code Playgroud)

ayn*_*ber 5

collect()->reject是建立在 之上的collect()->filter,而后者又使用array_filter. (Arr::where只是使用 array_filter 回调的简单方法)

/**
 * Run a filter over each of the items.
 *
 * @param  callable|null  $callback
 * @return static
 */
public function filter(callable $callback = null)
{
    if ($callback) {
        return new static(Arr::where($this->items, $callback));
    }

    return new static(array_filter($this->items));
}
Run Code Online (Sandbox Code Playgroud)

如文档中所述,Array keys are preserved, and may result in gaps if the array was indexed. The result array can be reindexed using the array_values() function.如果没有指定数组键,则使用默认的 0->n。当集合从 array_values() 返回时,显然不会删除索引;