Laravel保存多个记录

问题描述:

我有一个数组内的数组,并想添加一些东西。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 

    ] 
] 

你不改变$options所以foreach随每次迭代破坏$option。尝试这样的代替:

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

你应该使用对数组

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

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

$key属性做到这一点,它应该工作!

// $options would be like: 

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