生成月份& PHP中两个日期的年份数组
我从表单中两个 MM/YYYY
例如:
$start = "2/2016";
$end = "11/2017"
我需要所有月份和年份的输出 像这样在php
$monthArray = Array (
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
[5] => 7
[6] => 8
[7] => 9
[8] => 10
[9] => 11
[10] => 12
[11] => 1
[12] => 2
[13] => 3
[14] => 4
[15] => 5
[16] => 6
[17] => 7
[18] => 8
[19] => 9
[20] => 10
[21] => 11
);
$yearArray = Array (
[0] => 2016
[1] => 2016
[2] => 2016
[3] => 2016
[4] => 2016
[5] => 2016
[6] => 2016
[7] => 2016
[8] => 2016
[9] => 2016
[10] => 2016
[11] => 2017
[12] => 2017
[13] => 2017
[14] => 2017
[15] => 2017
[16] => 2017
[17] => 2017
[18] => 2017
[19] => 2017
[20] => 2017
[21] => 2017
);
功能会更好。请帮忙。提前致谢
答案 0 :(得分:6)
如果您想使用日期时间,您可以这样做:
SELECT ( (SELECT SUM(qty_claimed) As total_items_claimed
FROM so_claim_item
WHERE sales_order_id = 1
) =
(SELECT SUM(quantity) As total_items_ordered
FROM sales_order_item
WHERE sales_order_id = 1
)
) as is_same;
示例:http://sandbox.onlinephpfunctions.com/code/8bfa8cc9481aa8a13d83f62d9c1c6c7927654842
答案 1 :(得分:1)
<?php
$start = "2/2016";
$end = "11/2017";
$start = explode('/', $start);
$end = explode('/', $end);
$d1 = strtotime($start[1] . '-' . $start[0] . '-01');
$d2 = strtotime($end[1] . '-' . $end[0] . '-01');
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$month = [];
$year = [];
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$month[] = date('m',$min_date);
$year[] = date('Y',$min_date);
}
print_r($month);
print_r($year);
答案 2 :(得分:1)
这应该比现有的答案更快,使用更少的内存,因为它不依赖于日期对象的创建和操作(特别是将字符串解析为日期对象):
/**
* Takes start and end date string in format 'mm/yyyy' along with a $months and $years
* arrays; modifies the arrays in place to add all months and years between the dates
*/
function listMonthsAndYears($start, $end, &$months, &$years) {
list($startM, $startY) = array_map('intval', explode('/',$start));
list($endM, $endY) = array_map('intval', explode('/',$end));
$m = $startM;
$y = $startY;
while($endY > $y || ($endY === $y && $endM >= $m) ){
$months[]= $m;
$years[] = $y;
$m++;
if($m > 12){ // loop to the next year
$m = 1;
$y++;
}
}
}
用法:
$start = '2/2016';
$end = '11/2017';
listMonthsAndYears($start, $end, $months, $years);