2016-11-08 185 views
1

我有一個數組內的數組,並想添加一些東西。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 

    ] 
] 

回答

1

你不改變$options所以foreach隨每次迭代破壞$option。嘗試這樣的代替:

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

你應該使用對數組

// 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 
    ] 
]