如何为Laravel集合增值?

时间:2018-10-31 13:05:32

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

2 个答案:

答案 0 :(得分:3)

我怀疑有更干净的方法可以做到这一点,但这是我目前能想到的最好的方法。您还可以使用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);

答案 1 :(得分:2)

使用此

$data = Model::all();
$data[0]->foo = 'your data here';