如何为laravel集合增值? [英] How to put value on laravel collection?

查看:38
本文介绍了如何为laravel集合增值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在laravel集合的第一个元素上赋予价值?像 $ collection-> put('foo',1)这样的东西,但是会增加第一个元素的值.

How to put value on first element in laravel collection ? Something like that $collection->put('foo', 1) but adding value to the first element.

Collection {#376
  #items: array:1 [
    0 => array:9 [
      "id" => 83
      "status" => "offline"
      "created_date" => "Oct 31, 2018"
      // add foo => 1 here
    ]
  ]
}

推荐答案

我怀疑有更干净的方法可以做到这一点,但这是我目前能想到的最好的方法.您还可以使用 map transform 并对其发送到其闭包的键值进行比较,但是尽管如此,您仍然可能循环遍历数组的所有元素知道要定位的特定目标.

I suspect there's a cleaner way to do this, but this is the best I could come up with at the moment. You could also use map or transform with a comparison run on the key value that gets sent to their closures, but that would end up cycling through all elements of the array despite you knowing the specific one you want to target.

$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);

这篇关于如何为laravel集合增值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆