[英]First element in a while loop?
I am writing a PHP script that imports a csv and inserts into a table but i need to get the first row so i can have the field names..here is my csv 我正在编写一个PHP脚本导入csv并插入到表中,但我需要获取第一行所以我可以拥有字段名称..这是我的csv
id artist song
11 NewBee great stuff
10 anotherNewbee even better
6 NewArtist New song
As you can see the first row is the name of the fields that i need. 如您所见,第一行是我需要的字段的名称。 here is my loop
这是我的循环
$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"}
How do i get the first and put them in variables and continue the loop of the data using those fields in an insert statement 我如何得到第一个并将它们放入变量并使用insert语句中的那些字段继续数据循环
Would this work for you? 这对你有用吗?
$row = 1;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
if($row == 1) {
// do something
}
else
{
// do something
}
++$row;
}
在您的while块之前,只需运行一次fgetcsv函数并存储字段标题。
Either deepsat's or mattmoon9's methods will work fine. 无论是deepsat或者mattmoon9的方法都可以正常工作。 Here's what mattmoon9's answer would look like structured in code (also based on my comment on the answer):
这是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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.