0

ループに問題があります。

私はこのようなテキストファイルを持っています

アン・クセレラ

AN ビラ

AN ソルナス

アン・ソルデュ

AN シスポニー

アン・セグデット

アン・エル・タルター

AN サン ジュリア デ ロリア

AN サン ジョアン デ カセレス

200万行以上あることを除いて。

これを挿入用のSQLリクエストに入れる必要があります

過去12時間、私は成功していませんでした

私はこのように試しました

<?php
$file = "cities.txt";
$file_w = "cities.sql";
$f = fopen($file, "r");
$nf = fopen($file_w, "w+");

for($l = 0; $l<2; $l++){


$line = fgets($f);
$ex = preg_split('/\s+/', $line);

foreach($ex as $k => $v){

    echo $ex[0].' '. $ex[1];
    echo '<br>';

    $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");

}
}






fclose($f);
fclose($nf);
?>

またはこのように

$file = "cities.txt";
$file_w = "cities.sql";
$f = fopen($file, "r");
$nf = fopen($file_w, "w+");

while ($line = fgets($f, 4096000))  {
    // echo $line;


$ex = preg_split('/\s+/', $line);
// var_dump($ex);die();
foreach($ex as $k => $v){

    // echo $ex[0].' '. $ex[1];
    // echo '<br>';

    $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");



}
}





fclose($f);
fclose($nf);

しかし、どちらの場合も、書き込みファイルにこれがありました

('AN','Xixerella')

('AN','Xixerella')

('AN','Xixerella')

('あん','ビラ')

('あん','ビラ')

('あん','ビラ')

各行が 3 回繰り返されており、その理由がわかりません。

よろしくお願いいたします。

4

1 に答える 1

0

foreach ループが while ループにネストされているため、行が不必要に多くの部分に分割されており、ロジックに欠陥があります。

<?php
$infile = "cities.txt";
$outfile = "cities.sql";
$rh = fopen($infile, "r");
$wh = fopen($outfile, "w+");

//this has to change because a blank line or a line that is simply '0' will break the loop
while( ($line = fgets($rh, 4096000)) !== false ) {
    $parts = preg_split('/\s+/', $line, 2); //limit to splitting into TWO parts, state and city.
    $state = $parts[0];
    $city = preg_replace("/'/", '&#39;', $parts[1]); //replace stray apostrophes
    $output = sprintf("('%s','%s')\r\n", $state, $city)
    fwrite($wh, $output)
}

fclose($rh);
fclose($wh);
于 2013-08-01T00:12:01.227 に答える