douliedai4838 2016-03-18 08:33
浏览 27
已采纳

通过PHP从CSV获取数据

I am having one csv file with three columns and Name , month and expanses. The file name is : name.csv. The file format is like this.

NAME    MONTH   EXPANSES
JHON    JAN     200
GATES   JAN     150
JHON    MAR     150
BILL    APP     100

Whereas I am having one php file: name.php which will fetch the required data from the csv file and the sours code is:

<?php
$x="JHON"; // to be checked in the first column
  $handle = fopen("name.csv","r")or die("file dont exist");
  $output = '';
   while (!feof($handle )){
    $data = fgetcsv($handle,4096,",");
        if(($data[0] ==$x)){
           $output .= sprintf( "Month: %s     Expanses: %d)<br>", 
           $data[1], $data[2]);
        }
    }
echo $output;
fclose($handle);
?>

I want to sort out where the name is “JHON”, with the above code and the result is as following.

Month:  JAN            Expanses:  200 
Month:  MAR           Expanses:  150 
Month:  AUG           Expanses:  250

But what I want is heading like: Expanses of JHON and at bottom, total expenses: amount

MONTH WISE EXPANSES OF JHON 
Month:  JAN            Expanses:  200 
Month:  MAR           Expanses:  150 
Month:  AUG           Expanses:  250

TOTAL EXPANCES:   600

Can anybody help me in correcting the php code please?

  • 写回答

2条回答

  • doushao8399 2016-03-18 08:53
    关注

    Actually you already exctract data from your CSV. As far I understand it you only want to add a header at the top and a sum at the bottom.

    Why not just do something like this?

    <?php
        $x="JHON"; // to be checked in the first column
        $handle = fopen("name.csv","r") or die("file doesn't exist");
        $output = '';
        $total = 0;
    
        while (!feof($handle )){
            $data = fgetcsv($handle, 4096, ",");
            if(($data[0] == $x)){
                $output .= sprintf( "Month: %s     Expenses: %d)<br>", $data[1], $data[2]);
    
                $total += $data[2];
            }
        }
    
        fclose($handle);
    
        echo "MONTHLY EXPENSES OF " . $x . "<br/><br/>";
        echo $output . "<br/><br/>";
        echo "TOTAL EXPENSES:   " . $total;
    ?>
    

    Remark 2: It's "expense", "expance" is not a word

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog