PHP读取csv并使用fputcsv:如何使用if条件跳过整行

时间:2016-06-30 20:28:52

标签: php arrays fopen fputcsv

我正在尝试根据另一个csv源文件重新创建一个csv文件。当该行有一个特定的单词" WORDO"时,我试图跳过整行。现在我只能替换那些有" WORDO"通过一些空字符串("")。但是我想在找到匹配时跳过整行。现在$ keepColumns数组仍保持数据[1](空或不)我想跳过整行#34; WORDO"在$ data [1]

里面
<?php

$finalArray = array();
$newFinalData = "new_csv.csv";

if (($finalData = fopen("mycsv.csv", "r")) !== FALSE)
    {

    $newfile = fopen($newFinalData, 'w');

    while (($data = fgetcsv($finalData, 999999, ",",'"')) !== FALSE)
        {

        //If the 1st column has WORDO as text, ideally skip the whole row
        if( substr( $data[1], 0, 5 ) === "WORDO" ) {
            $data[1] = "";
        }

        $keepColumns = array(

            $data[0],
            $data[1],
            $data[2],
            $data[5]

        );

        fputcsv($newfile, $keepColumns, ";",'"');
        }
    fclose($finalData);
    fclose($newfile);
    }


?>

1 个答案:

答案 0 :(得分:2)

您应该使用关键字continue直接跳到下一次迭代:

        if( substr( $data[1], 0, 5 ) === "WORDO" ) {
            $data[1] = "";
            continue;
        }