i'm not so hot with my php.
i was wondering if you could help me, i'm trying to create an array that contains the last 31 dates. e.开发者_开发知识库g.
$dates = array("2011-03-22", "2011-03-21", "2011-03-20", "2011-03-19", ........... "2011-02-22");
any pointers appreciated :)
thanks
alsweet
Using the DateTime object, its fairly straight forward. (Available from PHP 5.2 onwards).
$dates = array();
$date = new DateTime();
for($i = 0; $i < 31; $i++) {
$dates[] = $date->format('Y-m-d');
$date->modify('-1 day');
}
Using DateInterval
:
foreach(new DatePeriod(new DateTime("30 days ago"), new DateInterval('P1D'), 30) as $d)
$a[] = $d->format('Y-m-d');
$a = array_reverse($a); // assuming you want today to be index 0
This is an older-school method using unix timestamps, mktime()
, and date()
.
<?php
// mktime() gives you a unix timestamp, with the
// current timestamp returned if you don't supply
// an argument.
$now = mktime();
$dates = array();
for ($i = 1; $i < 31; $i++) {
// date() allows you to format a unix timestamp.
// Take now (mktime()), and iteratively substract
// 60 seconds x 60 minutes x 24 hours (gives you
// one day in seconds), and multiply that by the
// days-in-seconds offset, or $i, and run that
// date() to produce the timestamp that date you
// will use to produce the plaintext formatted date.
$dates[$i-1] = date('Y-m-d',$now-($i*(60*60*24)));
}
?>
If you:
echo '<pre>';
print_r($dates);
You get the following:
Array
(
[0] => 2011-03-20
[1] => 2011-03-19
[2] => 2011-03-18
[3] => 2011-03-17
[4] => 2011-03-16
[5] => 2011-03-15
[6] => 2011-03-14
[7] => 2011-03-13
[8] => 2011-03-12
[9] => 2011-03-11
[10] => 2011-03-10
[11] => 2011-03-09
[12] => 2011-03-08
[13] => 2011-03-07
[14] => 2011-03-06
[15] => 2011-03-05
[16] => 2011-03-04
[17] => 2011-03-03
[18] => 2011-03-02
[19] => 2011-03-01
[20] => 2011-02-28
[21] => 2011-02-27
[22] => 2011-02-26
[23] => 2011-02-25
[24] => 2011-02-24
[25] => 2011-02-23
[26] => 2011-02-22
[27] => 2011-02-21
[28] => 2011-02-20
[29] => 2011-02-19
)
http://php.net/manual/en/function.date.php
http://www.php.net/manual/en/function.mktime.php
精彩评论