我正在尝试从CSV读取数据并将其写入新CSV,将数据拆分为多个文件,其中电子邮件地址($ row [14])在每个文件中都是唯一的。我正在阅读的CSV已经通过电子邮件地址订购了。这里的循环正常工作,除了正在创建的文件都只包含一行。如何修改此操作以将行写入仅包含唯一电子邮件地址的每个文件。
<?php
$file = fopen("yahrzeit-4.csv","r");
$x=1;
while ( $row = fgetcsv( $file, ";" ) ) {
if ($file) {
if ($email = $row[14] == $email) {
$filename = 'mailchimp'.$x.'.csv';
$fpR = fopen($filename, 'w');
$dataR = array( $row[2],
$row[3],
$row[14],
$row[6] . ' ' . $row[7] . ' ' . $row[8],
$row[11] . ' ' . $row[10] . ', ' . $row[12],
jdtogregorian ( jewishtojd($Hebmonth, $row[6], 5774 ))
);
$email = $row[14]; $x++;
}
else {
$x=1;
$fp = fopen('mailchimp.csv', 'w');
$data = array ( $row[2],
$row[3],
$row[14],
$row[6] . ' ' . $row[7] . ' ' . $row[8],
$row[11] . ' ' . $row[10] . ', ' . $row[12],
jdtogregorian ( jewishtojd($Hebmonth, $row[6], 5774 ))
);
}
$email = $row[14];
}
fputcsv($fpR, $dataR);
fputcsv($fp, $data);
}
fclose($fp);
fclose($fpR);
?>
答案 0 :(得分:1)
如果我理解正确,您似乎正在尝试创建包含其他CSV文件中记录的CSV文件。例外情况是,如果您发现重复的电子邮件地址,您希望这些地址为每个副本进入不同的文件,只要地址在每个文件中都是唯一的,就可以保留尽可能少的文件吗?
我显然没有检查过这个,因为我没有你的数据,但这应该有希望做你以后做的事情,把非唯一的电子邮件地址分成下一个可用的文件(对于那个地址) )。
<?php
$file = fopen("yahrzeit-4.csv","r");
$addresses = array(); //This will hold counters for each address
$fp = fopen('mailchimp.csv', 'w'); //This is the first list
$fp2 = array(); //This will hold handles for each subsequent csv, 1 for each non-unique address (although it may hold more than one address unique to the file)
if($file) {
while ( $row = fgetcsv( $file, ";" ) ) { //Read file
if(isset($addresses[$row[14]])) { //Email has been found before at least once
$targetfile = $addresses[$row[14]]; //Check the counter to find the next csv to write to for this particular address
if(!isset($fp2[$targetfile])) { //Check if it has already been opened
$fp2[$targetfile] = fopen('mailchimp'.$targetfile.'.csv', 'w'); //If not open it and store it in the array of file handles for later use
}
$dataR = array(
$row[2],
$row[3],
$row[14],
$row[6] . ' ' . $row[7] . ' ' . $row[8],
$row[11] . ' ' . $row[10] . ', ' . $row[12],
jdtogregorian ( jewishtojd($Hebmonth, $row[6], 5774 ))
);
fputcsv($fp2[$targetfile], $dataR); //Write data to this file handle
$addresses[$row[14]]++; //Increment counter for this email address so the next write will go into the next sequential file.
} else { //This is the standard write if the address is not a duplicate
$data = array (
$row[2],
$row[3],
$row[14],
$row[6] . ' ' . $row[7] . ' ' . $row[8],
$row[11] . ' ' . $row[10] . ', ' . $row[12],
jdtogregorian ( jewishtojd($Hebmonth, $row[6], 5774 ))
);
fputcsv($fp, $data);
$addresses[$row[14]] = 1;
}
}
foreach($fp2 as $handle) { //Close all handles
fclose($handle);
}
fclose($fp);
}
?>