开发者

list through file using a while loop

I cannot get this to work properly, I need the program to list through the records within the file, if $records[$row][2]is the same as the previous, it should repeat class 'field' with a new $records[$row][2], otherwise it should start a new #row. Please help!

if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {


    $prevRow2 = '';

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);

        $records[] = $data;

        echo 'Previous'. $prevRow2;
        echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";

        if ($records[$row][2] == $prevRow2) {

            for ($c=0; $c < $num; $c++) {
            if ($c != 1) {  
                echo "<div class=\"field\">" . $data[$c] . "</div>";
                }   
            }
            $prevRow2 = $records[$row][2];
            $row++;
        }
        else {
            echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
            for ($c=0; $c < $num; $c++) {
            if ($c != 1) {  
                echo "<div class=\"field\">" . $data[$c] . "</div>";
                }   
            }
            $prevRow2 = $records[$r开发者_JAVA百科ow][2];
            $row++;
            echo "</div>";
        }




    echo "</div>";
}
fclose($handle);

}


First of all, you seem to assume that your CSV file is ordered by the column you want to group on. If this is not the case, then you should first read the file, sort it, and then print it. If your CSV file is not too big for the memory of your server, this should work.

Also, your code has repetitions and store the entire file into an array (actually, just like I suggested above, but I don't know if it is intentional). try something like this:

This is my demo.csv:

"Banana", "yellow"
"Lemon", "yellow"
"Orange", "orange"
"Strawberry", "red"
"Tomato", "red"

This is the PHP to loop through it and list it by color:

<?php

if (($handle = fopen('demo.csv', "r"))) {
    $prev = false;
    while (($data = fgetcsv($handle, 1000, ","))) {
        if ($prev !== $data[1]) {
            $prev = $data[1];
            echo '<p><b>' . $prev . '</b></p>';
        }
        echo $data[0] . '<br>';
    }
}
fclose($handle);

?>

This is the output in HTML (I added some linebreaks for proper display here)

<p><b>yellow</b></p>
Banana<br>
Lemon<br>
<p><b>orange</b></p>
Orange<br>
<p><b>red</b></p>
Strawberry<br>
Tomato<br>

(If the CSV was not grouped by color, you'd need a different approach.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜