PHP 用不同的列迭代 CSV

PHP Iterating CSV with different columns

我有一个像这样定义的 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);

您可以检查 $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);

这是我的变体:

$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);