drmticpet66231422 2015-10-26 07:30
浏览 55
已采纳

从php中的csv文件返回第n行

I have a csv file and have created the code to read the whole file into a table thus:

$table = "<table id='availabilitytableData'>

";

$f = fopen("assets/temp/test.csv", "r");

while (($line = fgetcsv($f)) !== false) {

$table .= "<tr>";

foreach ($line as $cell) {
$table .= "<td style='font-size:9pt;'>" . htmlspecialchars($cell) . "</td>";
}

$table .= "</tr>
";
}

fclose($f);
$table .= "
</table>";
return $table;

What is the best approach to select say just the 4th row from the csv file? I have tried various approaches along the lines of

$line = file($f);//file in to an array
return $line[4];

which gives me the line I want but not in a formatted table. Other code snippets e.g. like this give clues but I can't seem to adapt them to my purpose. Bit stuck here I'm afraid any pointers are most welcome

  • 写回答

1条回答 默认 最新

  • douxing6434 2015-10-26 08:04
    关注

    What about something nice and simple like this:

    $lineNo = 1;  //initialise a pointer
    
    while (...) {
    
        if($lineNo == 4){
    
            //output line 4
    
            break;  //to prevent any more looping after line 4
        }
    
        $lineNo++;  //increment the pointer
    }
    

    Option 2

    Or.. ..just extract line 4 from $line and dont bother with a loop.

    $line = fgetcsv($f));
    
    $line4 = $line[3];  //arrays are zero-indexed
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: