如何一次修复laravel集合块循环?

时间:2019-10-13 15:34:36

标签: php arrays laravel chunking

我对带有大块结果的laravel收集有疑问。它仅循环运行一次。

我在数组中有204个元素,我想通过使用laravel集合助手将其分成100个。它必须运行三遍,但我只有一次。

    private function __migrateDistricts()
    {
        DB::beginTransaction();
        try {
            $file = 'resources/csv/districts.csv';
            $csv = array_map('str_getcsv', file($file));
            $table = 'districts';
            $collection = collect($csv);
            $arr_districts = array();
            foreach ($collection->chunk(100) as $districts) {
                foreach ($districts as $dist) {
                    array_push($arr_districts, $this->__transformDistricts($dist));
                }
                DB::table($table)->insert($arr_districts);
                DB::commit();
            }
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    private function __transformDistricts($district)
    {
        $code = substr($district[3],0,2);
        $pro = DB::table('provinces')->where('code', $code)->first();
        return [ 
            'province_id' => $pro->id,
            'name_kh' => $district[1],
            'name_en' => $district[2],
            'code' => $district[3],
        ];
    }

运行I之后,表中只有100条记录。表中应为204条记录。我的代码有什么问题?谢谢

1 个答案:

答案 0 :(得分:1)

在您的代码中...

$arr_districts = array();
foreach ($collection->chunk(100) as $districts) {
    foreach ($districts as $dist) {
        array_push($arr_districts, $this->__transformDistricts($dist));
    }
    DB::table($table)->insert($arr_districts);
    DB::commit();
}

在每个内部循环中,您将数据添加到$arr_districts中,该数据在您的第二个外部循环中仍将包含来自第一个循环的数据。

您应该为每个主循环重置此数组以清除数据...

foreach ($collection->chunk(100) as $districts) {
    $arr_districts = array();        // Move to here
    foreach ($districts as $dist) {
        array_push($arr_districts, $this->__transformDistricts($dist));
    }
    DB::table($table)->insert($arr_districts);
    DB::commit();
}