Laravel "Undefined offset: 4" 使用 faker 时出现异常,如何去除偏移量?
Laravel "Undefined offset: 4" exception when working with faker , how to remove the offset?
public function run(){
$types = ['Travelling','Camping','Restaurants','Food'];
for ($i = 0; $i < 50; $i++){
$faker = Factory::create();
$internet = new Internet($faker);
$date = new DateTime($faker);
$lorem = new Lorem($faker);
$id = $internet->numberBetween($min = 2000,$max = 2000000);
$price = $internet->randomFloat($nbMaxDecimals = 2, $min = 0, $max = 100);
$expiration = $date->dateTimeBetween($startDate = 'now', $endDate = '+2 years');
$title = $lorem->sentence($nbWords = 3, $variableNbWords = true);
DB::table('coupon')->insert([
'id'=>$id,
'title'=>$title,
'price'=>$price,
"type"=>$types[$i],
'expiration'=>$expiration
]);
}
}
table更新了4行。
需要你的帮助,请不明白如何克服偏移量限制?
任何额外的配置?
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined offset: 4","C:\xampp\htdocs\couponsystem\database\seeds\CouponSeeder.php")
肯定是因为您的变量类型仅由 4 个元素组成,当您的 foor 循环中的变量 i 为 4 时,它会抛出错误 undifined offset 4。解决此问题。
改变这个,"type" => $types[$i]
至,"type" => $types[rand(0, 3)]
你$types
数组只有4个元素,没有索引4
。
使用modulo 4确保数字永远不会超过 3 并保持从 0 到 3 的循环。
"type" => $types[$i % 4],
public function run(){
$types = ['Travelling','Camping','Restaurants','Food'];
for ($i = 0; $i < 50; $i++){
$faker = Factory::create();
$internet = new Internet($faker);
$date = new DateTime($faker);
$lorem = new Lorem($faker);
$id = $internet->numberBetween($min = 2000,$max = 2000000);
$price = $internet->randomFloat($nbMaxDecimals = 2, $min = 0, $max = 100);
$expiration = $date->dateTimeBetween($startDate = 'now', $endDate = '+2 years');
$title = $lorem->sentence($nbWords = 3, $variableNbWords = true);
DB::table('coupon')->insert([
'id'=>$id,
'title'=>$title,
'price'=>$price,
"type"=>$types[$i],
'expiration'=>$expiration
]);
}
}
table更新了4行。 需要你的帮助,请不明白如何克服偏移量限制? 任何额外的配置?
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined offset: 4","C:\xampp\htdocs\couponsystem\database\seeds\CouponSeeder.php")
肯定是因为您的变量类型仅由 4 个元素组成,当您的 foor 循环中的变量 i 为 4 时,它会抛出错误 undifined offset 4。解决此问题。
改变这个,"type" => $types[$i]
至,"type" => $types[rand(0, 3)]
你$types
数组只有4个元素,没有索引4
。
使用modulo 4确保数字永远不会超过 3 并保持从 0 到 3 的循环。
"type" => $types[$i % 4],