如何为 Laravel 集合中的第一个元素赋值?类似于 $collection->put('foo', 1)
但为第一个元素添加值。
Collection {#376
#items: array:1 [
0 => array:9 [
"id" => 83
"status" => "offline"
"created_date" => "Oct 31, 2018"
// add foo => 1 here
]
]
}
最佳答案
我怀疑有一种更干净的方法可以做到这一点,但这是我目前能想到的最好的方法。您还可以使用 map
或 transform
对发送到闭包的键值进行比较,但这最终会循环遍历数组的所有元素,尽管您如此了解您想要定位的具体目标。
$collection = collect([
[
'id' => 83,
'status' => 'offline',
'created_date' => 'Oct 31, 2018'
]
]);
$firstKey = $collection->keys()->first(); //This avoids the unreliable assumption that your index is necessarily numeric.
$firstElement = $collection->first();
$modifiedElement = array_merge($firstElement, ['foo1' => 1]);
$collection->put($firstKey, $modifiedElement);
关于php - 如何让 Laravel 收藏增值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084061/