如何存储与提供的数字相同的数据?
示例
存储abc
、10
次
abc
和10
都来自表单请求
代码
nonuiqueAmount: 10
nonuiqueSerial: "abc"
if(!empty($request->input('nonuiqueSerial'))) {
foreach($request->input('nonuiqueAmount') as $item) { // this returns error
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
错误:
为foreach((提供的参数无效
您应该使用for循环:
// nonuiqueAmount: 10
// nonuiqueSerial: "abc"
if (!empty($request->input('nonuiqueSerial'))) {
for ($i = 0; $i < $request->input('nonuiqueAmount', 0); ++$i) { // I've added the zero as a default value to prevent unnecessary loops
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
foreach循环仅适用于数组,用于循环遍历数组中的每个键/值对。w3schools文档
您的nonuiqueAmount
就是int
。我建议简单地坚持基本的循环
for ($x = 0; $x < $request->input('nonuiqueAmount'); $x++) {
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}