我想从 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);
答案 0 :(得分: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
附加到数组,
内嵌数组元素并写入文件简而言之,你:
\n
这是换行符,
答案 1 :(得分:-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));