带Fwrite()的PHP循环并写入文件

时间:2018-10-16 18:02:12

标签: php foreach fwrite ord

我已经有一个循环,在名为results.txt的文本文件中打印“ mason is a a o n”。

现在,我正在处理一个循环以打印名称中的每个字母“ m的十进制表示形式是109,m的二进制表示形式是1101101 m的十六进制表示形式是6d m的八进制表示形式是155”。我已经弄清楚了这部分,但是我需要对名称中的每个字母进行遍历,然后将表示形式写入result.txt。

我认为我需要使用一个foreach循环,该循环类似于我在第一个fwrite语句中使用的循环。我不知道如何设置它。这是我到目前为止的内容:

<?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>";

?>

1 个答案:

答案 0 :(得分: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;

?>

我尝试过了,而且行得通。请甚至阅读代码中的注释