簡體   English   中英

如何在PHP中找到“ fgetcsv” while()循環的最后一次迭代

[英]How to find the last iteration of a “fgetcsv” while() loop in PHP

如何找到最后的迭代:

這是一個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);
}

}

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM