PHP 生成日期范围

PHP Generate day range

我正在尝试生成天数范围,from 1 to 28,其中日期的英语序数后缀。例如:1st of month2nd of month...

for($i = 1; $i <= 28; $i++)
{
    $arrayRange[] = date('dS', strtotime($i));
}

echo "<pre>";
print_r($arrayRange);
echo "</pre>";

输出:

Array
(
    [0] => 01st
    [1] => 01st
    [2] => 01st
    ...
    [26] => 01st
    [27] => 01st
)

我做错了什么..?

你可以这样使用:

$arrayRange[] = (new DateTime('Aug '.$i))->format('jS');

试试这个,它使用“+1 天”等上下文日期功能将您的整数注册为一天:)

要回答你的第二个问题——就像你做错了什么一样——你将一个整数传递给 function that expects a string

<?php
for($i = 0; $i <= 27; $i++)
{
//The February is there to keep '1st' a '1st' even on days when it's not 
//the '31st'
$arrayRange[] = date('dS', strtotime("1st february +".$i.' day'));
}

echo "<pre>";
print_r($arrayRange);
echo "</pre>";

输出:

Array
(
    [0] => 01st
    [1] => 02nd
    ...
    [28] => 28th
)¨

编辑:
要删除 0,您可以像这样使用 ltrim():

$arrayRange[$i] = ltrim(date('dS', strtotime("1st february +".$i.' day')), "0");

这会给你这样的输出

    [0] => 1st
    [1] => 2nd
    ...
    [28] => 28th

编辑 2: 固定它。提示 MLF 注意到错误。

您应该将正确的时间戳作为日期函数的第二个参数传递并使用 j(不带前导零)日期格式:

list($m, $y) = explode('-', date('m-Y'));
for($d = 1; $d <= 28; $d++)
{
    $arrayRange[] = date('jS', mktime(0, 0, 0, $m, $d, $y));
}
echo "<pre>";
print_r($arrayRange);
echo "</pre>";