2016-08-23 18 views
2

可以说你有这样的简单集合:如何更改集合中最后一项的值?

$c = collect([ 
    ['active'=>false], 
    ['active'=>false], 
    ['active'=>false], 
    ] 
); 

我想改变的最后一个项目设置活动为true 有没有简单的collectionish的方式,而不是像一些:

$collection->toArray(); 
$collection[count($collection)-1]['active'] = true; 
$newCollection = collect($collection); 

回答

0

首先所有laravel集合都是可访问的,您无需致电toArray。 至于你发出你可以这样做:

$last = $collection->pop(); $last['active'] = true $collection->push($last)

https://laravel.com/docs/5.2/collections#method-pop https://laravel.com/docs/5.2/collections#method-push

+0

感谢这么简单,就像我知道的pop()方法和推(),而不是在我的脑海:) –

+0

它连接使用* last()*方法的操作更少:'$ collection-> last()['active'] = true;' – miikes

+2

使用'last()'可以检索值,但不能修改https:// github。 COM /照亮/支撑/团块/ c371bff488ce3ec3270091d77cf2e825cfeb74f3/Arr.php#L157 –

相关问题