しばらくループで最初の要素?
-
28-09-2019 - |
質問
CSVをインポートしてテーブルに挿入するPHPスクリプトを書いていますが、フィールド名を持つことができるように最初の行を取得する必要があります。
id artist song
11 NewBee great stuff
10 anotherNewbee even better
6 NewArtist New song
ご覧のとおり、最初の行は私が必要とするフィールドの名前です。これが私のループです
$handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
print_r($data);
//do something with it but i need the first time around
array(3) { [0]=> string(2) "id" [1]=> string(6) "artist" [2]=> string(4) "song" }
array(3) { [0]=> string(2) "11" [1]=> string(6) "NewBee" [2]=> string(1) "great stuff" }
array(3) { [0]=> string(2) "10" [1]=> string(13) "anotherNewbee" [2]=> string(1) "even better"}
最初のものを取得して変数に配置し、挿入ステートメントでそれらのフィールドを使用してデータのループを続行するにはどうすればよいですか
解決
これはあなたのために働きますか?
$row = 1;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
if($row == 1) {
// do something
}
else
{
// do something
}
++$row;
}
他のヒント
whileブロックの前に、FGETCSV関数を1回実行してフィールド見出しを保存するだけです。
DeepSatまたはMattmoon9のメソッドのいずれかが正常に機能します。これが何ですか Mattmoon9の答え コードで構造化されたように見えます(回答に関する私のコメントにも基づいて):
$handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r');
if (($columns = fgetcsv($handle, 1000, ',')) !== false) {
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
// Process data
}
// Insert into database using $columns as table column names
} else {
// The file couldn't be parsed as CSV
}
所属していません StackOverflow