-1

我想从apriori_main表中获取一些整数并将它们作为逗号分隔值存储到文本文件中。对于每次迭代,我都会file_put_contents在下一行写入数据。使用fwrite给出相同的结果。

我想要在文本文件中的输出是:

1,2,3,4

但我得到的输出是:

1  
,2  
,3  
,4  

这是代码片段:

$y="";
$stmt='SELECT category FROM apriori_main where id='.$id.''; 
$nRows = $conn->query('select count(category) from apriori_main where id='.$id.'')->fetchColumn(); 
echo $nRows;

$file = "/opt/lampp/htdocs/ghi.txt";
$f = fopen($file, 'a+'); // Open in write mode
$count=1;

foreach($conn->query($stmt) as $row)
{ 
    if($count!=$nRows) 
    {
        $user = $row['category']."\n"; 
        $y=$user; $y=$y.",";
        $str=$y; echo $y;
        $count=$count+1;
    }
    else
    { 
        $user = $row['category']."\n";
        $y=$user; $str=$y; echo $y; 
    }
    file_put_contents($file, $str, FILE_APPEND);
}
fclose($f);
4

2 回答 2

0

这就是所有需要的:

$stmt = 'SELECT category FROM apriori_main where id='.$id.''; 
$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $str[] = $row['category'];
}
file_put_contents($file, implode(',', $str));
// only use FILE_APPEND if needed for the next time to append
  • 遍历查询结果行
  • 追加category到数组
  • 用逗号内爆数组元素,并写入文件

简而言之,您:

  1. 不需要查询计数
  2. 不需要打开文件
  3. 不要使用\n那是换行符
  4. 不需要,在循环中添加逗号
  5. 不要编写每个循环迭代
于 2017-04-10T17:37:31.490 回答
-1

我不知道您还对这些值做了什么,但您似乎有大量不必要的变量声明。

我认为你可以有效地打破这一切

 $file = "/opt/lampp/htdocs/ghi.txt";
      $f = fopen($file, 'a+'); // Open in write mode
        $count=1;


      foreach($conn->query($stmt) as $row)
      { 
         if($count!=$nRows) 
         {
            $user = $row['category']."\n"; 
            $y=$user; $y=$y.",";
            $str=$y; echo $y;
            $count=$count+1;
         }
         else
         { 
            $user = $row['category']."\n";
            $y=$user; $str=$y; echo $y; 
         }
         file_put_contents($file, $str, FILE_APPEND);
     }
         fclose($f);

到此为止(最后只有一个文件操作)

$file = "/opt/lampp/htdocs/ghi.txt";

foreach($conn->query($stmt) as $row)
{ 
    $y[] = $row['category']; 
}
//output to screen
echo implode("<br>", $y);
//output to file
file_put_contents($file,implode(",", $y));
于 2017-04-10T18:02:14.277 回答