PHP-如何将for循环的结果写入文件

时间:2018-10-16 14:22:39

标签: php xampp fopen fwrite

我正在尝试在数组的每个部分中运行一个for循环,并打印出一条消息,指出“泥瓦匠是拼写的”。我了解如何写入文件,也了解使用for循环打印出数组中的每个元素,但是我不了解如何将数据从for循环输出转换为可放入fwrite函数的变量。这是我到目前为止的内容:

<?php
$name = "mason";
$nameLetterArray = str_split($name);
$results = fopen("results.txt", "w");
fwrite($results, $forLoopOutput); //here forLoopOutput would be the "m a s o n" part
fclose($results);

$length = count($nameLetterArray);
for ($i = 0; $i < $length; $i++) {
print $nameLetterArray[$i];
}

2 个答案:

答案 0 :(得分:0)

您可以对一个文件使用多个fwrite(),最后,您将关闭文件指针,如下所示:

<?php
$name = "mason";
$nameLetterArray = str_split($name);
$results = fopen("results.txt", "w");
fwrite($results, $forLoopOutput);

// Here you'll write each letter:
for ($i = 0; $i < count($nameLetterArray); $i++) {
  fwrite($results, $nameLetterArray[$i];
}

fclose($results);
?>

答案 1 :(得分:0)

您已经虚拟编写了代码,只需进行一些更改...

$name = "mason";
$nameLetterArray = str_split($name);
$results = fopen("results.txt", "w");
// Create output string to save multiple writes
$output = "";
$length = count($nameLetterArray);
for ($i = 0; $i < $length; $i++) {
     //print $nameLetterArray[$i];
    $output .= $nameLetterArray[$i]." ";  // Add letter followed by a space
}
// Write output
fwrite($results, $name." is spelt ".$output); 
// Close file
fclose($results);

您也可以在循环中使用foreach()

$name = "mason";
$nameLetterArray = str_split($name);
$results = fopen("results.txt", "w");
fwrite($results, $name." is spelt "); 
// Create output string to save multiple writes
$output = "";
foreach ($nameLetterArray as $nameLetter) {
     //print $nameLetterArray[$i];
    $output .= $nameLetter." ";  // Add letter followed by a space
}
// Write output
fwrite($results, $name." is spelt ".$output); 
// Close file
fclose($results);

或者(最后)您可以使用implode()而不是循环...

$output = implode(" ", $nameLetterArray);