我从php循环获得双输出

时间:2014-04-11 05:59:04

标签: php csv fgetcsv

我的数据输出两次,我不知道为什么。它应该是每行一个fname和lname。

<?php

$row = 1;
if (($handle = fopen("nameList1.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "    ")) !== FALSE) {
        $num = count($data);
        //$result = explode($data);
        echo "<br />\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
                //echo $data[$c];
                echo $data[0];
                echo " ";
                echo $data[1];
        }
    }
    fclose($handle);
}

** * ** 输出 ** * ** * ** * **

Nancy AlvordNancy Alvord
Lucy HadacLucy Hadac
Laura LundgrenLaura Lundgren
Judy PigottJudy Pigott
Thomas BayleyThomas Bayley
Barbara BrownBarbara Brown
Aaron DixonAaron Dixon
Jennifer HadlockJennifer Hadlock
Molly AdolfsonMolly Adolfson
Susan AnsteadSusan Anstead
Shannon BraddockShannon Braddock
Isa D’ArleansIsa D’Arleans
Elizabeth DavisElizabeth Davis
William DonnellyWilliam Donnelly

4 个答案:

答案 0 :(得分:0)

试试这个

$row = 1;
if (($handle = fopen("nameList1.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "    ")) !== FALSE) {
    $num = count($data);
    //$result = explode($data);
    echo "<br />\n";
    $row++;
    echo $data[0];
    echo " ";
    echo $data[1];
}
fclose($handle);
}

答案 1 :(得分:0)

for ($c=0; $c < $num; $c++) {
    echo $data[0] . " " . $data[1];
}

由于每行有两个不同的数据(fname,lname),$ num总是等于2.

两次,你会打印$ data [0]&amp; $ data [1];)

你必须这样做:

echo $data[0];
echo $data[0];

或者如果你绝对想要使用for语句:

for ($c=0; $c < $num; $c++) {
    echo $data[$c] . " ";
}

答案 2 :(得分:0)

你得到所有csv字段两次因为,while循环中的for循环从0开始,它应该是1到0或

答案 3 :(得分:0)

试试这个:

$file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r"); 

    //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
            $record['contact_email'] = $data[2];
            $record['subject'] = $_REQUEST['subject'];
            $record['message'] = $_REQUEST['message'];
            $record['status'] = 0;

            $oAdminEmail->insertQueEmail($record);
            } 
    } while ($data = fgetcsv($handle,1000,",","'"));