为什么在没有列出 foreach 中的所有行时得到未定义的偏移量?
Why do I get undefined offset when not listing all the rows in foreach?
我在尝试使用查询生成器将一些 excel 数据导入数据库时遇到问题,我得到了未定义的偏移量:4,即使我拥有的数据列超过 4。数据:excel data。关于 foreach 有什么我应该知道的吗?
public function collection(Collection $rows)
{
$no = 1;
foreach ($rows as $row) {
DB::table('data_train')->insert([
'no_pendaftaran' => $no,
'nama' => $row[1],
'jalur' => $row[4],
'tahun' => $row[5],
'daftar_kembali' => $row[10],
]);
$no++;
var_dump($row);
}
}
var_dump($row) 输出:txt var_dump
由于您不知道每次迭代的输出,因此您应该首先检查您尝试插入的变量是否确实有任何数据。尝试类似的东西:
'jalur' => (! empty($row[4])) ? $row[4] : null,
相同的原则适用于您的所有插入字段。
确保您的数据库字段接受 nullable
否则将 null
替换为 ''
'jalur' => $row[4] ?? null
或将其用于不可为 null 的字段
'jalur' => $row[4] ?? ''
我在尝试使用查询生成器将一些 excel 数据导入数据库时遇到问题,我得到了未定义的偏移量:4,即使我拥有的数据列超过 4。数据:excel data。关于 foreach 有什么我应该知道的吗?
public function collection(Collection $rows)
{
$no = 1;
foreach ($rows as $row) {
DB::table('data_train')->insert([
'no_pendaftaran' => $no,
'nama' => $row[1],
'jalur' => $row[4],
'tahun' => $row[5],
'daftar_kembali' => $row[10],
]);
$no++;
var_dump($row);
}
}
var_dump($row) 输出:txt var_dump
由于您不知道每次迭代的输出,因此您应该首先检查您尝试插入的变量是否确实有任何数据。尝试类似的东西:
'jalur' => (! empty($row[4])) ? $row[4] : null,
相同的原则适用于您的所有插入字段。
确保您的数据库字段接受 nullable
否则将 null
替换为 ''
'jalur' => $row[4] ?? null
或将其用于不可为 null 的字段
'jalur' => $row[4] ?? ''