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

PHP - How to write the result of a for loop to a file

我试图让一个 for 循环 运行 遍历数组的每个部分并打印出一条消息 "mason is spelled m a s o n"。我了解如何写入文件,也了解如何使用 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];
}

您可以对一个文件使用多个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);
?>

由于您已经虚拟编写了代码,因此只需进行少量更改...

$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);