[当我尝试在存储功能的控制器中使用For循环提交数据时
public function store(Request $request)
{
$tender = new TenderMaster;
$tender->bid_name = $request->bid_name;
$tender->bid_year = $request->bid_year;
$tender->shipping_mode = $request->shipping_mode;
$tender->start_date = $request->start_date;
$tender->end_date = $request->end_date;
$explodeval = explode(",",$request->origin_port);
$tender->freight_forwarder = $request->freight_forwarder;
$tender->save();
for($i=0;$i<=count($explodeval);$i++){
$tender->airPorts()->attach($explodeval[$i]);
}
return back();
}
简单数组从索引0开始,以索引count()-1结尾
$my_array=['foo','bar','baz'];
// > 3
echo count($my_array)
// > 'foo'
echo $my_array[0]
// > 'baz'
echo $my_array[2]
// error
echo $my_array[3]
尝试一下:
for($i=0; $i<count($explodeval); $i++){
$tender->airPorts()->attach($explodeval[$i]);
}
您的错误是因为您使用了条件$i <= count(...
,这意味着如果使用count($array) == 3
,您将获得执行0, 1, 2, 3
的循环。这是4个元素,而不是3个元素。
您在数组中没有4个元素,并且没有索引$array[3]
。
您可以尝试阅读php文档:https://www.php.net/manual/en/control-structures.for.php