[英]PHP Loop With Fwrite() and Writing to a File
我已經有一個循環,可將“梅森拼寫為梅森”打印到一個名為result.txt的文本文件中。
現在,我正在處理一個循環,以打印名稱中的每個字母“ m的十進制表示為109的二進制表示形式為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>";
?>
如果您想在mason
之后使用它,可以這樣編寫另一個循環:
<?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;
?>
我試過了,它起作用了。 請閱讀代碼中的注釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.