我是PHP的初学者,也是编码的初学者。我有以下代码,增加月份。
if (isset($_REQUEST['Receipts'])) {
$months = array( " 31 Jan 2000"," 28 Feb 2000"," 31 Mar 2000","30 Apr 2000","31 May 2000",
"30 Jun 2000","31 Jul 2000"," 31 Aug 2000","30 Sep 2000","31 Oct 2000",
"30 Nov 2000","31 Dec 2000");
foreach ($months as $month){
$params['Date'] = '31 Jan 2000';
$response = $Auth->request('GET', $Auth->url('Receipts/Travel', 'core'), $params);
if ($Auth->response['code'] == 200) {
$receipt = $Auth->parseResponse($OAuth->response['response'], $Auth->response['format']);
pr($receipt->Receipts);
}
else
{
outputError($Auth);
}
}
我已经使用了将月值存储在数组中并循环它的基本示例。我想知道如何增加月值而不是直接将其存储在数组中,因为我需要编辑其他年份的代码,这是不可行的。任何人都能对此有所帮助吗?
由于
答案 0 :(得分:1)
喜欢这个?
if (isset($_REQUEST['Receipts'])) {
$months = array( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
$year=2000;
foreach ($months as $i=>$month) {
// Because arrays are 0-indexed, and cal_days_in_month takes the month number 1-indexed
$monthNumber=$i+1;
$numberOfDaysInMonth=cal_days_in_month(CAL_GREGORIAN, $monthNumber, $year);
$params['Date'] = "$numberOfDaysInMonth $month $year";
$response = $Auth->request('GET', $Auth->url('Receipts/Travel', 'core'), $params);
if ($Auth->response['code'] == 200) {
$receipt = $Auth->parseResponse($OAuth->response['response'], $Auth->response['format']);
pr($receipt->Receipts);
} else {
outputError($Auth);
}
}
?>
另外,我认为您可以从查看PHP的DateTime()类中受益: http://www.w3schools.com/php/php_ref_date.asp
答案 1 :(得分:1)
for ($i = 1; $i <= 12; $i++) {
$time = strtotime("last day of 2000-$i-01");
$date = date('j M Y');
... your other stuff here...
}
strtotime()计算该月的最后一天,将其作为当天上午12:00:00的时间戳(例如2014-12-31 00:00:00)返回,然后将其格式化为您的友好“ 2000年12月31日“。
如果您需要更多年份,那么只需在所有这些周围添加另一个循环,然后以这种方式生成/检索年份值。
答案 2 :(得分:1)
您实际上可以使用专为此类任务设计的deticated类 - DatePeriod
$year = '2050';
$iterator = new DatePeriod("R11/$year-01-01T00:00:00Z/P1M");
foreach ($iterator AS $month) {
$month->modify('last day of this month');
var_dump($month);
}
请注意这可以让您:
“R11 / 2050-01-01T00:00:00Z / P1M”是ISO 8601字符串,其中:
在foreach循环中,我们可以使用 modify('本月最后一天'),以便将日期设置为当月的最后一天。并且你有它 - 这样你就可以按升序获得DateTime对象,代表一个月的最后一天,每年的每个月。要将这些对象转换为字符串,请查看DateTime format方法。