根据条件php创建CSV文件并添加数据

我有一组结果,我想为它创建 csv 文件。但如果结果有效,我想将电子邮件添加到有效的 csv 文件中,如果它无效,则添加到无效的 csv 文件中。但我无法做到这一点。它将所有电子邮件添加到清理 csv 文件,无效的 csv 为空。有什么建议么


结果是这样的:


Array

(

    [0] => Array

        (

            [email] => tamas.szabo@millionverifier.com

            [result] => valid

        )


    [1] => Array

        (

            [email] => support@millionverifier.com

            [result] => valid

        )


)

这是我的条件


// creating dirty and clean file

$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');

$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');


// adding headers to them

fputcsv($clean_emails, $headers);

fputcsv($dirty_emails, $headers);            


if ($results[$i]['result'] === 'valid') {


    // adding clean emails to csv

    foreach ($results as $row) {

    fputcsv($clean_emails, $row);

    }

    fclose($clean_emails);


} elseif ($results[$i]['result'] === 'invalid') {


    // adding dirty emails to csv

    foreach ($results as $row) {

    fputcsv($dirty_emails, $row);

    }

    fclose($dirty_emails);


} else {


    // if there are not any dirty or clean emails add them unknown to csv

    $unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');

    fputcsv($unknown_emails, $row);

    fclose($unknown_emails);


}


繁华开满天机
浏览 126回答 1
1回答

慕的地8271018

也许你想要逐行分离?// creating dirty and clean file$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');$unknown_emails = null; // No file yet// adding headers to themfputcsv($clean_emails, $headers);fputcsv($dirty_emails, $headers);            foreach ($results as $row) { // Scan each row    if ($row['result'] === 'valid') {        fputcsv($clean_emails, $row);    } elseif ($row['result'] === 'invalid') {        fputcsv($dirty_emails, $row);    } else {  // found something else        if (!isset($unknown_emails)) { // Open file if it was not            $unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');            fputcsv($unknown_emails, $headers); // Add headers ?        }        fputcsv($unknown_emails, $row);    }} // end loopfclose($clean_emails);fclose($dirty_emails);if (isset($unknown_emails)) {    fclose($unknown_emails); // Close 'unknown' if it was opened}
打开App,查看更多内容
随时随地看视频慕课网APP