Fwrite在foreachloop PHP中
我想将数组的内容写入新文件 就目前而言,我的文件只包含数组的最后一个元素,而不是前两个元素。因此,output2.txt文件中的文本仅为Edward 我是不是误解了什么Fwrite在foreachloop PHP中,php,foreach,fwrite,Php,Foreach,Fwrite,我想将数组的内容写入新文件 就目前而言,我的文件只包含数组的最后一个元素,而不是前两个元素。因此,output2.txt文件中的文本仅为Edward 我是不是误解了什么 $array = array ("Sarah", "William", "Edward"); foreach ($array as $value) { $myfile = fopen("output2.txt", "w") or die("Unable to open file!"); fwrite($myfi
$array = array ("Sarah", "William", "Edward");
foreach ($array as $value) {
$myfile = fopen("output2.txt", "w") or die("Unable to open file!");
fwrite($myfile,$value);
fclose($myfile);
}
您每次尝试都在创建新文件,这可能会对您有所帮助
<?php
$array = array ("Sarah", "William", "Edward");
$txt = "";
foreach ($array as $value) {
$txt = $txt . $value;;
}
$myfile = fopen("output2.txt", "w+") or die("Unable to open file!");
fwrite($myfile,$txt);
fclose($myfile);
?>
不要在循环中包含文件操作函数,创建一个字符串,然后将其写入文件
就像@Dagon建议的那样,您可以使用内爆函数简单地内爆一个数组
<?php
$array = array ("Sarah", "William", "Edward");
$txt = implode(",", $array);
$myfile = fopen("output2.txt", "w+") or die("Unable to open file!");
fwrite($myfile,$txt);
fclose($myfile);
?>
阵列内爆的效率比循环内爆更高(需要改进:)
<?php
$array = array ("Sarah", "William", "Edward");
$txt = implode(",", $array);
$myfile = fopen("output2.txt", "w+") or die("Unable to open file!");
fwrite($myfile,$txt);
fclose($myfile);
?>