你如何列出随机日期(从最早到最新)?
我一直在努力用PHP实现这一目标,但没有成功。我可以得到一个随机的日期来显示,但一遍又一遍地循环相同的日期而不是创建新的并按指定的顺序列出它们。
到目前为止,这是我的代码:
// Create a random date between 2 months
$datestart = strtotime('01-11-2012');
$dateend = strtotime('01-12-2012');
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
for($i=0; $i< rand(10, 30) ;++$i)
{
echo "<div>" . date("d/m/Y", $datestart + ($randomday * $daystep)) ."</div>";
}
更新:由于 Mihai Iorga ,我现在设法让代码正常工作,但仍然存在将日期从最旧到最新排序的问题。我如何实现这一目标:
// Create a random date between 2 months
$datestart = strtotime('01-11-2012');
$dateend = strtotime('01-12-2012');
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
for($i=0; $i< rand(10, 30) ;++$i)
{
$randomday = rand(0, $datebetween);
echo "<div>" . date("d/m/Y", $datestart + ($randomday * $daystep)) ."</div>";
}
答案 0 :(得分:1)
$datestart = strtotime('01-11-2012');
$dateend = strtotime('01-12-2012');
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$dateArray[] = date("d/m/Y");
$randomday = rand(0, $datebetween);
for($i=0; $i< rand(10, 30) ;++$i)
{
$randomday = rand(0, $datebetween);
$randomdate = date("d/m/Y", $datestart + ($randomday * $daystep));
$dateArray[] = $randomdate;
}
sort($dateArray);
foreach ($dateArray as $d)
{
echo "<div>" . $d ."</div>";
}
在http://writecodeonline.com/php/上测试代码并运行此输出:
05/11/2012
06/11/2012
07/11/2012
08/11/2012
08/11/2012
12/11/2012
12/11/2012
12/11/2012
19/11/2012
20/11/2012
24/11/2012
27/11/2012
28/11/2012
30/11/2012
答案 1 :(得分:0)
你可以尝试
$dateStart = new DateTime();
$dateStart->setDate(2012, 11, 01);
$dateEnd = new DateTime();
$dateEnd->setDate(2012, 12, 01);
$dates = array();
while ( $dateStart < $dateEnd ) {
$dates[] = $dateStart->format("d/m/Y");
$dateStart->modify(sprintf("+%d day",mt_rand(1, 10)));
}
var_dump($dates);
输出
array
0 => string '01/11/2012' (length=10)
1 => string '07/11/2012' (length=10)
2 => string '14/11/2012' (length=10)
3 => string '20/11/2012' (length=10)
4 => string '27/11/2012' (length=10)
5 => string '28/11/2012' (length=10)