简体   繁体   中英

PHP Last in array to CSV

I have been trying to get this code to work for ages now and have looked at other questions but it is not working for me. Any guidance is greatly appreciated.

In context, there is a sql query to bring back all of the results for today's entries. These are converted to a CSV file every day. To import into the software then the end of each row must return "" and a carriage return except the last row which should not add a carriage return.

The code is below:

    $xo1 = "\"\"";
    $xo2 = "\r\n";

    while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
    $output .='"'.$row["$i"].'",';

    if(++$i === $columns_total){
    $xo1 = "";
    $xo2 = "";}
    }
    $output .= $xo1;
    $output .= $xo2;
    }

I guess rtrim() should do the job, if I got the question right.

while ( $row = mysql_fetch_array( $sql ) ) {
    foreach( $row as $column ) {
        $output .= sprintf( '"%s",""' . "\r\n" , $column );
    }
}
rtrim( $output, '""' . "\r\n" );

You can also use the index of the loop for this problem. When index is above zero apply the $xo1 and $xo2. For example:

for ($i = 0; $i < $columns_total; $i++) {
    if ( $i > 0 ) {
        $output .= $xo1 . $xo2;
    }

    // now apply other workings
    $output .='"'.$row["$i"].'",';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM