将rand()中的结果保存到新文件中


Save results form rand() to new files?

我想弄清楚如何将rand()函数的结果保存到10个不同的文件。

下面是我的代码:

<?php 
for($i = 0; $i < 10; $i++)
{
    $rand_valuec = rand(0,16); 
    echo "<b>Your Lucky Number is</b>: " . $rand_valuec . " <br />";
    $fp = fopen("results.php", "w");
    fwrite($fp, $rand_valuec); 
    fclose($fp);
}

:

Your Lucky Number is: 6 
Your Lucky Number is: 16 
Your Lucky Number is: 16 
Your Lucky Number is: 8 
Your Lucky Number is: 6 
Your Lucky Number is: 10 
Your Lucky Number is: 13 
Your Lucky Number is: 5 
Your Lucky Number is: 6 
Your Lucky Number is: 5 

results.php 包含:

5

我需要将每个结果保存到一个新文件;例如:1result.php, 2result.php, 3result.php, 4result.php, ..., 10result.php。什么好主意吗?: -)谢谢!

你可以把你的文件打开为:

$fp = fopen($i."result.php", "w");

<?php 
for($i=0; $i < 10; $i++)
{
$rand_valuec = rand(0,16); 
echo "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
$fp = fopen($i."results.php", "w");
fwrite($fp, $rand_valuec); 
fclose($fp);
}
?>

试一试:

<?php 
$numberOfFiles = 10;
$numberOfLinesPerFile = 10;
$path = "/home/your-user/your-path/";
for ($fileIndex = 1; $fileIndex <= $numberOfFiles; $fileIndex++) {
    $contentFile = "";
    for ($i = 0; $i < $numberOfLinesPerFile; $i++) { 
        $rand_valuec = rand(0,16); 
        $content = "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
    }
    file_put_contents($path . $fileIndex . "result.php", $content);
}