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

PHP-如何将for循环的结果写入文件,php,xampp,fopen,fwrite,Php,Xampp,Fopen,Fwrite,我试图在数组的每个部分都运行一个for循环,并打印出一条消息,上面写着“mason拼写为m a s o n”。我知道如何写入文件,我知道如何使用for循环打印数组中的每个元素,但我不知道如何将for循环输出的数据转换成可以放入fwrite函数中的变量。以下是我到目前为止的情况: <?php $name = "mason"; $nameLetterArray = str_split($name); $results = fopen("results.txt", "w"); fwrite($r

我试图在数组的每个部分都运行一个for循环,并打印出一条消息,上面写着“mason拼写为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];
}
您可以对一个文件使用multiple,最后关闭文件指针,如下所示:

<?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);
或者(最后)您可以使用
内爆()
而不是循环

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

只需将fwrite移到循环内,将fclose移到循环后谢谢,我知道foreach可以使它更简洁,但我对for更满意,这两个def都有助于我学习
$output = implode(" ", $nameLetterArray);