Laravel保存多条记录

时间:2016-11-08 11:06:58

标签: php arrays laravel

我在数组中有一个数组,想要添加一些东西。

$options = $request->options;
foreach ($options as $option) {
    $option['poll_id'] = $this->id;
}

dd($options);

但由于某种原因,它不会添加到数组中。

所以我收到了这个:

array:1 [
  0 => array:1 [
    "name" => "testtest"
  ]
]

但我希望如此:

array:1 [
  0 => array:1 [
    "name"    => "testtest",
    "poll_id" => 1 

  ]
]

2 个答案:

答案 0 :(得分:1)

您应该使用数组上的$key属性

// Suppose your $request->options is like:
$options = [
  0 => [
    "name" => "testtest"
  ]
];

foreach ($options as $key => $option) {
    $options[$key]['poll_id'] = 3; // Changing variable - $options here.
}

它应该有效!

// $options would be like:

array:1 [▼
  0 => array:2 [▼
    "name" => "testtest"
    "poll_id" => 3
  ]
]

答案 1 :(得分:1)

您不会更改$options,因此foreach会在每次迭代时销毁$option。尝试这样的事情:

$options = [];
foreach ($request->options as $key => $value) {
    $options[$key]['poll_id'] = $this->id;
}