0

我已经有一个循环,可以将“mason is spelled maso n”打印到一个名为 results.txt 的文本文件中。

现在我正在制作一个循环来打印名称中每个字母的“m 的十进制表示是 109 m 的二进制表示是 1101101 m 的十六进制表示是 6d m 的八进制表示是 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>";

?>
4

1 回答 1

1

如果你想要它之后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;

?>

我试过这个并且它有效。请阅读代码中的注释

于 2018-10-16T19:26:32.507 回答