I read in a csv file by using a while loop:
while (($data = fgetcsv($handle, null, ",")) !== FALSE)
and i want to skip the first row because this is the title row and i want to display on the screen "first line skipped".
if($data[0]=="title")
echo "Title row..skipping<br />";
else
//do stuff
The problem is since its in a while开发者_如何学JAVA loop it prints out "Title row...skipping" a bunch of times shown here:
Checking row 0...
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Checking row 1...
what should i do so it only prints it out once? does it have something to do with php's output buffering?
Or call fgetcsv($handle, null, ",")
once without assignment, to move the handler forward by one line:
fgetcsv($handle, null, ",");
while (($data = fgetcsv($handle, null, ",")) !== FALSE) {
// do stuff
}
if($data[0]=="title") {
if (!$skipped) {
echo "Title row..skipping<br />";
$skipped = true;
}
}
else
//do stuff
If you know for a certain that you only need to skip the first line then;
if(!$skipped)
{
echo "Title row..skipping<br />";
$skipped = true;
}
else
//do stuff
I think it'd be more elegant to use foreach:
foreach data as item {
if (item == "title") {
echo "Skipping title<br/>";
}
}
How you have it now, you are checking if (data[0] == "title")
every time you loop. data[0]
will always equal "title", so it will always evaluate to true. You could increment an $index
variable and do something like if (data[$index] == $title)
then $index++
near the bottom of the loop, but why do that when foreach
will essentially do that for you.
精彩评论