我的CSV定义与此数据类似。
"PID", "FName", "LName", "Email"
2425751712402934017,
1037862, "Jason", "Van Hooser", "jvanhooser@example.com"
961741, "Alana", "Traxler", "atraxler@example.com"
1100854, "Emily", "Walcheck", "ewalcheck@example.com"
1166892, "Mary", "Thomas", "mthomas@example.com"
8853065679823467777,
1179079, "Donna", "Thimm", "dthimm@example.com"
927671, "Lillian", "Wasson", "lwasson@example.com"
1175139, "Barry", "Tollison", "btollison@example.com"
1058086, "Christina", "Viktorin", "cviktorin@example.com"
我需要做的是遍历它,当涉及到只有带有长数字的PID字段的行时,我需要将它存储在变量($ wkey)中然后在插入中使用它声明。我知道我们可以将值放在每一行上,但输出文件的过程不能这样做。
Hwere是我的代码:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) {
$flag = false;
continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
}
fclose($handle);
我如何修改它来做我需要的?
以下是工作代码:
// skip header line
$data = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// get wkey for lines that has empty second column
if(trim($data[1]) == "") {
$wkey = $data[0];
}
if(trim($data[1]) != "") {
$import = "INSERT into exp_wb_bulk_registrations(`WebinarKey`, `PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
echo $import."<br />";
}
}
fclose($handle);
答案 0 :(得分:0)
您只需检查$data
数组的大小即可。类似的东西:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(count($data) == 4){
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
} else if(count($data) == ?) {
//DO STUFF
}
}
fclose($handle);
答案 1 :(得分:0)
这是我的变体:
$wkey = ''; // just for sure
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if(count($data)==1) { // hey, we found a wKey! let's remember it
$wkey = $data[0]; continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
}
fclose($handle);