首页 > 解决方案 > 如何为 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
    ]
  ]
}

标签: phplaravel

解决方案


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

推荐阅读