douweng7233 2013-09-10 14:45
浏览 16
已采纳

如何从每列中获取值并将它们组合成一个循环中的字符串

I have a CSV File which is lay out as so:

Column1     Column2    Column3
34            56          7
45            55         10
34            40         12

And code that does the following.

$row=1
if (($handle = fopen("report.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if($row == 1){ $row++; continue; }
        $num = count($data);
        $row++;


        $column1 = $column1 . ", ". $data[1];
        $column2 = $column2 . ", ". $data[2];
        $column3 = $column3 . ", ". $data[3];



}
fclose($handle);
}

$column1 = ltrim ($column1 ,','); //removes first comma from string
$column2 = ltrim ($column2 ,',');
$column3 = ltrim ($column3 ,',');

This produces three strings, which are needed to plot a graph.

"34,45,34"
"56,55,40"
"7,10,12"

However it is likely that I will be adding more columns to the csv file, so I need a way of looping around to avoid having to manually add new lines each time. I cannot seem to find a way to perform a loop which would give the variable names automatically for the columns without it breaking.

Any advice?

  • 写回答

1条回答 默认 最新

  • douhao8456 2013-09-10 14:52
    关注

    Use an array of strings for columns instead of $column1,2,3..:

        ...
        $num = count($data);
        $row++;
    
        for($i=0; $i<$num; $i++){
            $columns[$i] = $columns[$i] . ", ". $data[$i];
        }
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度