【问题标题】:How to find the last iteration of a "fgetcsv" while() loop in PHP如何在 PHP 中找到“fgetcsv”while() 循环的最后一次迭代
【发布时间】:2013-05-28 11:10:24
【问题描述】:

如何找到最后一次迭代:

这是一个 while 循环示例。我需要找到最后一次迭代,以便不会在末尾添加逗号。这是怎么做到的?

for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        $isfirst = true;
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            if ($isfirst){
                $isfirst = false;
                continue;
        }
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].'],');
        }
        fclose($handle);
    }
}

答案:

for($i=0;$i<count($files);$i++){
if (($handle = fopen($files[$i], "r")) !== FALSE) {
    $isfirst = true;
    $firstline = true;
    while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
        if ($isfirst){
            $isfirst = false;
            continue;
        }
        if ($firstline) {
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].']');
            $firstline = false;
        } else {
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, ',['.(int)$timestamp.','.(float)$data[2].']');
        }
    }
    fclose($handle);
}

}

【问题讨论】:

  • 反之亦然:在除第一行之外的每一行的开头添加一个逗号
  • 这是一个绝妙的主意。但是让我更新代码(我只包含了需要的内容)。我实际上并没有使用第一次迭代,因为那是标题。

标签: php while-loop iteration fgetcsv


【解决方案1】:
for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        $firstLine = TRUE;
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            if (!$firstLine) {
                fputs($out, ',');
            } else {
                firstLine = FALSE;
            }
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].']');
        }
        fclose($handle);
    }
}

【讨论】:

  • 哦,实际上,我认为这会起作用。让我插上电源,我会回复你的。
  • 不得不稍微修改一下,但想法已经到位。感谢您的帮助!
猜你喜欢
  • 2016-04-23
  • 2023-04-07
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 2021-05-27
  • 2013-05-17
  • 2015-10-20
相关资源
最近更新 更多