如何访问Laravel集合中的第n个项目?

Džu*_*ris 11 laravel laravel-collection

我想通过刻意制作一个重复的问题来打破所有规则......

其他问题有一个公认的答案.它显然解决了问题,但它没有回答标题问题.

让我们从头开始 - 该first()方法实现如下:

foreach ($collection as $item)
    return $item;
Run Code Online (Sandbox Code Playgroud)

它显然比采用$collection[0]或使用其他建议的方法更健壮.

即使集合中有20个项目,也可能没有索引0或索引的15项目.为了说明这个问题,让我们从文档中取出这个集合:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'desk'],
    ['product_id' => 'prod-200', 'name' => 'chair'],
]);

$keyed = $collection->keyBy('product_id');
Run Code Online (Sandbox Code Playgroud)

现在,我们是否有任何可靠的(最好是简洁的)方式来访问第n项$keyed

我自己的建议是:

$nth = $keyed->take($n)->last();
Run Code Online (Sandbox Code Playgroud)

但是这会给出错误的item($keyed->last())$n > $keyed->count().如果第n个项目存在并且null它不仅仅是first()表现,我们怎样才能得到第n个项目?

编辑

为了澄清,让我们考虑一下这个集合:

$col = collect([
    2 => 'a',
    5 => 'b',
    6 => 'c',
    7 => 'd']);
Run Code Online (Sandbox Code Playgroud)

第一项是$col->first().如何获得第二个?

$col->nth(3)应该返回'c'(或者'c'如果是0,但是会与之不一致first()).$col[3]不会工作,它只会返回一个错误.

$col->nth(7)应该返回,null因为没有第七项,只有四项.$col[7]不行,它会回来'd'.

您可以将问题改为"如何在foreach顺序中获取第n个项目?" 如果某些人更清楚的话.

Ale*_*nin 15

我想更快更省内存的方法是使用slice()方法:

$collection->slice($n, 1);
Run Code Online (Sandbox Code Playgroud)

  • Mkay,然后 `$collection->slice($n, 1)->fiirst()` 将返回第 n 个项目(如果它存在),否则返回 `null`。看起来很棒:) (2认同)

Ami*_*pta 8

您可以使用以下values()函数尝试:

$collection->values()->get($n);
Run Code Online (Sandbox Code Playgroud)

  • 它是工作解决方案,但它会复制整个集合并可能会杀死一个应用程序,如果集合本身很大(具有关系或类似的文章的集合). (2认同)

Ham*_*awy 7

你可以使用offsetGet因为Collection类实现ArrayAccess

$lines->offsetGet($nth);
Run Code Online (Sandbox Code Playgroud)


Muh*_*uqy 5

根据 Alexey 的回答,您可以在 AppServiceProvider 中创建一个宏(将其添加到 register 方法中):

use Illuminate\Support\Collection;

Collection::macro('getNth', function ($n) {
   return $this->slice($n, 1)->first();
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以在整个应用程序中使用它:

$collection = ['apple', 'orange'];

$collection->getNth(0) // returns 'apple'
$collection->getNth(1) // returns 'orange'
$collection->getNth(2) // returns null
$collection->getNth(3) // returns null
Run Code Online (Sandbox Code Playgroud)