简体   繁体   English

PHP最后在数组到CSV

[英]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. 在上下文中,有一个SQL查询可以返回今天条目的所有结果。 These are converted to a CSV file every day. 它们每天都会转换为CSV文件。 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. 我想rtrim()应该做的工作,如果我有正确的问题。

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. 当index高于零时,应用$ xo1和$ xo2。 For example: 例如:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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