我只需要一些脚本方面的帮助 - 我想将每 100 兰特数保存在
目录下的不同文本文件中 - 所以每次我让循环生成兰特数字每 100 个随机数我想将它们保存在不同的文本文件中,所以这是如何工作的,但我不知道如何将每个 100 兰特号码保存在它不存在的不同文本文件中
<?php
function randz()
{
$file_path = $_SERVER['DOCUMENT_ROOT'] . "testing/files/";
$content = NULL;
$start = 1111111;
$ofset = 9999999;
$counter = 1;
for($i=1; $i <= 500; $i++)
{
if( $i == 100 )
{
$rand = mt_rand($start, $ofset) * 999999;
$cut = substr($rand, 0,7);
$content .= $i .'-'. $cut."'r'n";
$file_path = $_SERVER['DOCUMENT_ROOT'] . "testing/files/"."text_".$counter++."_".$counter++.".txt";
continue;
}
}
$fp = fopen( $file_path , "wb" );
fwrite($fp,$content);
fclose($fp);
}
randz();
?>
如果
可以的话,我将首先对您的代码进行一些评论:
<?php
function randz()
{
$file_path = $_SERVER['DOCUMENT_ROOT'] . "testing/files/";
$content = NULL; // You are appending strings,
// so in order to avoid a type cast, you'd prefer:
$content = "";
$start = 1111111;
$ofset = 9999999;
$counter = 1;
for($i=1; $i <= 500; $i++)
{
// Why a loop and then an if with == ?
// Maybe you wanted to use if( ($i % 100) == 0 ) ?
if( $i == 100 )
{
$rand = mt_rand($start, $ofset) * 999999;
$cut = substr($rand, 0,7);
$content .= $i .'-'. $cut."'r'n";
$file_path = $_SERVER['DOCUMENT_ROOT'] . "testing/files/"."text_".$counter++."_".$counter++.".txt";
// Never pre/post increment twice the same
// variable in the same line.
// Does that increment counter in 1, or two?
continue;
}
}
$fp = fopen( $file_path , "wb" );
fwrite($fp,$content);
fclose($fp);
}
randz();
?>
为什么不只是,
<?php
function randz($file_number)
{
$file_path = $_SERVER['DOCUMENT_ROOT'] . "testing/files/";
$content = array();
$start = 1111111;
$ofset = 9999999;
$counter = 1;
for($i = 0; i < 100; i++)
{
$rand = mt_rand($start, $ofset) * 999999;
$cut = substr($rand, 0, 7);
$content[] = $i . "-" . $cut;
}
$str_content = implode("'r'n", $content);
file_put_contents($file_path ."text_" . $filenumber . ".txt", $str_content);
}
for($i = 0; $i < 500; $i++)
{
randz($i);
}
?>
我质疑你现有的很多代码。因此,我将回答这个问题:
如何使用PHP将兰德数字保存在不同的TXT文件中
看看file_put_contents()
.
举个简单的例子:
for ($i = 0; $i < 100; ++$i) {
file_put_contents("{$i}.txt", rand());
}
尝试:
function randz($fileCount){
$file_path = $_SERVER['DOCUMENT_ROOT'].'testing/files/text_';
$content ='';
for($i=1,$l=$fileCount+1; $i<$l; $i++){
for($n=1; $n<101; $n++){
$rand = (string)(mt_rand(1111111, 9999999) * 999999);
$cut = substr($rand, 0,7);
$content .= $n.'-'.$cut."'r'n";
}
file_put_contents($file_path.$i.'.txt', $content);
}
}
// create 10 files width 100 random content lines
randz(10);