2012-11-06 52 views
0

如何列出随机日期(从最早到最新)?从最早到最新订单随机排列日期

我一直在试图用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>"; 
} 

更新:我现在设法得到的代码工作得益于米哈伊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

包括'$ randomday = rand(0,$ datebetween);'in'for'会让你开始。你可以创建一个数组并使用'array_unique'来唯一。 –

+2

已经在所以,给这个阅读:http://stackoverflow.com/questions/1972712/generate-random-date-between-two-dates-using-php – RelicScoth

+0

我已经更新了问题的家伙,仍然有问题整理从最旧到最新日期 – methuselah

回答

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 
+0

嗨,我'我已经测试过你的代码,但它没有正确排序日期 – methuselah

+0

尝试更新的代码,看看它是否工作。 – chridam

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) 
+0

我看你是如何抛出阵列,但我怎么才能得到它显示日期内的唯一日期 – methuselah

+0

所有你需要的是http://pastebin.com/9PaAdLKA – Baba