6

我正在编写一个导入 csv 并插入到表中的 PHP 脚本,但我需要获取第一行,以便我可以拥有字段名称..这是我的 csv

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"} 

我如何获得第一个并将它们放入变量中并使用插入语句中的这些字段继续数据循环

4

3 回答 3

17

这对你有用吗?

$row = 1;

while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
    if($row == 1) {
        // do something
    }
    else
    {
        // do something
    }

    ++$row;
}
于 2010-11-02T02:25:01.030 回答
3

在您的 while 块之前,只需运行一次 fgetcsv 函数并存储字段标题。

于 2010-11-02T02:23:56.837 回答
2

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
}
于 2010-11-02T02:42:19.653 回答