我需要将一个变量指定为包含循环的函数的输出。
当前功能:
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,"
我需要返回一串日期,但它似乎只是在函数中拉出最后一个日期。
寻找类似:“2014-08-08,2014-08-07,2014-08-06,2014-08-05,2014-08-04,”
答案 0 :(得分:1)
您可以通过更改此行来解决此问题:
$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) . ',';
}
答案 1 :(得分:0)
目前,您使用每个赋值覆盖$ theRange的先前值,您需要使用字符串追加运算符&#34;。=&#34;并为$ 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;
}