在CSV文件的末尾附加括号

时间:2015-04-07 10:24:58

标签: php mysql csv

在内容的开头和结尾处,我必须附加括号,我的csv文件看起来像这样

        date1,success,failure,count
        1427653800,95,65,160
        1427653800,30,10,40
        1427740200,10,8,18
        1427740200,30,38,68
        1427826600,38,20,58
        1427826600,60,10,70
        1427653800,15,15,30
        1427653800,10,10,20 

添加括号后,内容应如下所示:[1427653800,95,65,160] 我的PHP代码如下:

    <?php
        $list = array ('date1', 'success', 'failure','count');

        $sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
              $users_profile_user_id = mysqli_query($conn, $sql); 

          $fp = fopen("data.csv", "w");

            fputcsv($fp, $list);
        while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
        {

          fputcsv($fp, $row);

        }

        fclose($fp);
    ?> 

this is my conn.php file ,please suggest me on this

4 个答案:

答案 0 :(得分:1)

最好使用此查询

 $sql = "SELECT CONCAT('[','',(SUBSTRING(UNIX_TIMESTAMP(date1),1,10))),success,failure,CONCAT(count,'',']') from h_statistics";

它给你的结果像[1427653800,95,65,160]所以你不需要在循环中做任何代码

答案 1 :(得分:0)

尝试追加并添加括号:

$row[0] = '['.$row[0];
$row[3] .= ']';
fputcsv($fp, $row);

答案 2 :(得分:0)

尝试使用我的函数,即将文本添加到关联数组的第一个和最后一个元素:

<?php

function array_brackets($array,$prefix,$suffix){

//add prefix to the first element
end($array);
$key = key($array);
$array[$key] = $prefix . $array[$key];

//add sufix to the last element
reset($array);
$key = key($array);
$array[$key] = $array[$key] . $suffix;

return $array;
}


$list = array ('date1', 'success', 'failure','count');

$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
      $users_profile_user_id = mysqli_query($conn, $sql); 

  $fp = fopen("data.csv", "w");

    fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{

  fputcsv($fp, array_brackets($row,"[","]"));

}

fclose($fp);

?> 

答案 3 :(得分:0)

请运行此代码并输出输出:

<?php

$list = array ('date1', 'success', 'failure','count');

$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
      $users_profile_user_id = mysqli_query($conn, $sql); 

  //$fp = fopen("data.csv", "w");

  //fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{

  //fputcsv($fp, array_brackets($row,"[","]"));
  print_r($row);
  exit;
}

//fclose($fp);

?>