php - 如何为 laravel 收藏赋予价值?
问题描述
如何为 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);
推荐阅读
- java - 为什么不鼓励在 Java 程序中使用全局变量?
- apache-spark - 将 spark2 依赖项、avro 数据块添加到 zeppelin 0.7.3 时出错
- c# - 如何将 RS256 算法与 RSACryptoServiceProvider 一起使用
- mongodb - 从 Kubernetes 中的另一个服务访问服务
- google-sheets - 自动清除单元格
- html - 有没有办法将 HTML 直接写入 Outlook 邮件正文?
- php - 为什么 PHP set_execption_handler 会捕获 Error 对象
- jenkins - 禁用詹金斯重播
- java - 要同步哪些对象?为什么局部变量不好?
- javascript - 在 img onmouseover 函数中使用 this 和 document.getElementById