这是我的代码,当我运行这个函数时,我得到了这个:Warning: array_push() expects parameter 1 to be array 但是我$printed在开始之前定义为一个数组.
$printed = array();
function dayAdvance ($startDay, $endDay, $weekType){
$newdateform = array(
'title' => date("M d", strtotime($startDay))." to ".date("M d", strtotime($endDay)). $type,
'start' => $startDay."T08:00:00Z",
'end' => $startDay."T16:00:00Z",
'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);
array_push($printed, $newdateform);
if ($weekType=="weekend"){
$days="Saturday,Sunday";
}
if ($weekType=="day"){
$days="Monday,Tuesday,Wednesday,Thuresday,Friday";
}
if ($weekType=="evening"){
$days="Monday,Tuesday,Wednesday";
}
$start = $startDate;
while($startDay <= $endDay) {
$startDay = date('Y-m-d', strtotime($startDay. ' + 1 days'));
$dayWeek = date("l", strtotime($startDay));
$pos = strpos($dayWeek, $days);
if ($pos !== false) {
$newdateform = array(
'title' => date("M d", strtotime($start))." to ".date("M d", strtotime($endDate)). $type,
'start' => $startDate."T08:00:00Z",
'end' => $startDate."T16:00:00Z",
'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);
array_push($printed, $newdateform);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 18
在array_push()调用的范围内,$printed从未初始化.将其声明为global或包含在函数参数中:
$printed = array();
.
.
.
function dayAdvance ($startDay, $endDay, $weekType){
global $printed;
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
要么
function dayAdvance ($startDay, $endDay, $weekType, $printed = array()) { ... }
Run Code Online (Sandbox Code Playgroud)
注意:
更快的替代方法array_push()是使用[]以下方法将值附加到数组:
$printed[] = $newdateform;
Run Code Online (Sandbox Code Playgroud)
此方法将自动检测变量是否从未初始化,并在附加数据之前将其转换为数组(换句话说,没有错误).
更新:
如果希望值$printed保持在函数之外,则必须通过引用传递它或将其声明为global.以上示例不相同.以下示例等同于使用global(事实上,它是一种比使用更好的做法global- 它会强迫您更加谨慎地使用代码,防止意外的数据操作):
function dayAdvance ($startDay, $endDay, $weekType, &$printed) { ... }
Run Code Online (Sandbox Code Playgroud)