我需要分配一个变量作为包含循环的函数的输出。
当前功能:
function dateRange($numberofDays){
while($x<=$numberofDays) {
$currentNumber = "-" . $x . " days";
$date = DATE('Y-m-d', STRTOTIME($currentNumber));
$theRange = $date . ",";
$x++;
}
return $theRange;
}
当前结果:
echo dateRange(7); // outputs a single date "2014-08-02,"
我需要返回一串日期,但它似乎只在函数中拉取 LAST 日期。
查找类似以下内容:">
您可以通过更改此行来解决此问题:
$theRange = $date . ",";
要使用.=
而不是=
:
$theRange .= $date . ",";
当前代码正在覆盖 $theRange
的值,而不是追加到它。
编辑:您也可以使用数组:
function dateRange($numberOfDays){
$dates = array();
for ($i = 0; $i < $numberOfDays, $i++) {
$dates[] = date('Y-m-d', strtotime("-" . $i . " days"));
}
// Join the array elements together, separated by commas
// Also add an extra comma on the end, per the desired output
return implode(',', $dates) . ',';
}
目前,您在每次赋值时都会覆盖之前的 $theRange 值,您需要使用字符串追加运算符".="并为$theRange赋值,如下所示:
function dateRange($numberofDays){
$theRange = ""; //added this line
while($x<=$numberofDays) {
$currentNumber = "-" . $x . " days";
$date = DATE('Y-m-d', STRTOTIME($currentNumber));
$theRange .= $date . ","; //changed this line
$x++;
}
return $theRange;
}