PHP 使用 Fwrite() 循环并写入文件

PHP Loop With Fwrite() and Writing to a File

我已经有一个循环将 "mason is spelled m a s o n" 打印到名为 results.txt 的文本文件中。

现在我正在努力获得一个循环来为名称中的每个字母打印 "Decimal representation of m is 109 Binary representation of m is 1101101 Hexadecimal representation of m is 6d Octal representation of m is 155"。我已经弄清楚了这部分,但我需要为名称中的每个字母创建一个循环,然后将表示写入 results.txt.

我想我需要使用一个类似于我在第一个 fwrite 语句中使用的循环的 foreach 循环。我不知道如何设置它。这是我目前所拥有的:

<?php
$name = "mason";
$nameLetterArray = str_split($name);

$results = fopen("results.txt", "w");

$output = " ";

foreach ($nameLetterArray as $nameLetter) {
$output .= $nameLetter." ";
}

fwrite($results, $name." is spelt ".$output);
fclose($results);

//here is what i need the loop to do for each letter in the name and save to 
//.txt file
$format = "Decimal representation of $nameLetterArray[0] is %d";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Binary representation of $nameLetterArray[0] is %b";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Hexadecimal representation of $nameLetterArray[0] is %x";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";
$format = "Octal representation of $nameLetterArray[0] is %o";
echo sprintf($format, ord($nameLetterArray[0]));
echo "<br>";

?>

如果你想在 m a s o n 之后使用它,你可以这样写另一个循环:

<?php
$name = "mason";
$nameLetterArray = str_split($name);

$results = fopen("results.txt", "w");

$output = " ";

foreach ($nameLetterArray as $nameLetter) {
$output .= $nameLetter." ";
}

foreach($nameLetterArray as $nameLetter){

    $format = "Decimal representation of $nameLetter is %d";
    $output.="\n\n".sprintf($format, ord($nameLetter));

    $format = "Binary representation of $nameLetter is %b";
    $output.="\n\n".sprintf($format, ord($nameLetter));

    $format = "Hexadecimal representation of $nameLetter is %x";
    $output.="\n\n".sprintf($format, ord($nameLetter));

    $format = "Octal representation of $nameLetter is %o";
    $output.="\n\n".sprintf($format, ord($nameLetter));

}


//then write the result into the file

fwrite($results, $name." is spelt ".$output);
fclose($results);

//if you want to see the output in the browser replace the \n by <br>
$output=str_replace("\n","<br>",$output);
echo $output;

?>

我试过了,很管用。请阅读代码中的评论