php - 如何让 Laravel 收藏增值?

标签 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
    ]
  ]
}

最佳答案

我怀疑有一种更干净的方法可以做到这一点,但这是我目前能想到的最好的方法。您还可以使用 maptransform 对发送到闭包的键值进行比较,但这最终会循环遍历数组的所有元素,尽管您如此了解您想要定位的具体目标。

$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/

相关文章:

php - 使用下拉菜单和文本输入在 mysql 数据库上执行 AJAX 搜索

php - 将 wordpress 站点从 Nginx 移动到专用服务器 Windows

php - 自定义路由文件上的 Laravel 路由缓存

javascript - 如何在 laravel 中应用客户端密码加密

php - html编码输出&&不正确的字符串错误

php - $_POST 不回应查询

php - 在 Laravel url 中使用 bootstrap glyphicon

php - 根据用户输入在 Laravel 中创建新表?

laravel - 如何在标签 Blade 模板中创建增量 1?

php - 从服务器向客户端发送数据?