Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 557
Matt Elhotiby Avatar asked Nov 02 '10 02:11

Matt Elhotiby


1 Answers

Would this work for you?

$row = 1;

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

    ++$row;
}
like image 166
zerodin Avatar answered Oct 10 '22 02:10

zerodin