【问题标题】:Laravel "Undefined offset: 4" exception when working with faker , how to remove the offset?使用 faker 时 Laravel “未定义偏移量:4”异常,如何删除偏移量?
【发布时间】:2020-01-22 00:11:02
【问题描述】:
    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
        ]);
    }
}

表格更新了 4 行。 需要您的帮助不明白如何克服偏移限制? 任何额外的配置?

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined offset: 4","C:\xampp\htdocs\couponsystem\database\seeds\CouponSeeder.php")

【问题讨论】:

  • $types 中只有 4 个条目,但您循环了 50 次,所以一旦索引为 4,它就会中断。

标签: laravel faker


【解决方案1】:

$types数组只有4个元素,没有索引4

使用modulo 4 确保数字永远不会超过 3 并保持从 0 到 3 的循环。

"type" => $types[$i % 4],

【讨论】:

    【解决方案2】:

    肯定是因为您的变量类型仅由 4 个元素组成,当您的 foo 循环中的变量 i 为 4 时,它会抛出错误 undifined offset 4。要解决这个问题。

    改变这个,"type" => $types[$i]

    至,“类型” => $types[rand(0, 3)]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2015-12-20
      • 2014-06-25
      • 2020-01-02
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多