csv php索引无法正常工作

时间:2014-02-25 09:19:37

标签: php csv

我有一个csv文件“food.csv”,详细信息按以下顺序排列。总行数是10和第5列。我想通过php将文件编入索引以获取“芒果”数组。

ITEM,DESC,QTY,RATE,TYPE
124,APPLE,20,300,NEW
123,MANGO,10,500,NEW
135,BANANA,30,600,OLD
148,ORANGE,12,40,NEW
111,MANGO,20,150,OLD
125,APPLE,7,100,OLD

以下是PHP代码,但它无效。

<?php
$eurl = "http://www.xyz.com/food.csv";
if (($handle = fopen ( $eurl, "r" )) !== FALSE) {
    $keys = fgetcsv ( $handle, 1000, ";" );
    while ( ($data = fgetcsv ( $handle, 1000, ";" )) !== FALSE ) {
if ($r2->id == "MANGO") {
        $found = true;
        break;
    }

        $res[] = array_combine($keys, $data);
    }
    fclose ($handle);
}
var_dump($res);
?>

我以下列方式要求结果。任何人都可以帮我纠正代码吗?

当索引键为“MANGO”时,它应该输出为:

MANGO 10 Kgs @ 500USD(123-NEW)

MANGO 20 Kgs @ 150USD(111 -OLD)

2 个答案:

答案 0 :(得分:0)

此外,当您无法可视化正在生成的数组时,它是一个数组而不是一个对象添加一些调试代码,如此

<?php
    $eurl = "http://www.xyz.com/food.csv";
    if (($handle = fopen ( $eurl, "r" )) !== FALSE) {
        $keys = fgetcsv ( $handle, 1000, "," );

        $output = '';

        while ( ($data = fgetcsv ( $handle, 1000, "," )) !== FALSE ) {
            var_dump( $data );
            if ($data[1] == "MANGO") {
                $found = true;

                $output .= sprintf( "%s %d Kgs @ %dUSD (%d-%s)\n", 
                                   $data[1],
                                   $data[2],
                                   $data[3],
                                   $data[0],
                                   $data[4]
                                 );
            }
            // this makes no sense here, but I dont know what you were trying to do at this point
            $res[] = array_combine($keys, $data);
        }
        fclose ($handle);
    }

    echo $output;

    var_dump($res);
?>

答案 1 :(得分:0)

$handle = fopen("$link_file","r")or die("file dont exist");
$output = '';
while (!feof($handle )){
    $data = fgetcsv($handle,4096,",");
        if($data[1] =="MANGO"){
          $output .= sprintf( "%s %d Kgs @ %dUSD (%d-%s)<br>", 
                                       $data[1],
                                       $data[2],
                                       $data[3],
                                       $data[0],
                                       $data[4]
                                       );
        }

}
echo $output;
fclose($handle);

这将回应:

MANGO 10 Kgs @ 500USD (123-NEW)
MANGO 20 Kgs @ 150USD (111-OLD)