这是我的代码,当我运行此函数时,我得到以下信息: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);
}
}
}
最佳答案
在调用array_push()
的范围内,从未初始化$printed
。将其声明为global
或将其包含在函数参数中:
$printed = array();
.
.
.
function dayAdvance ($startDay, $endDay, $weekType){
global $printed;
.
.
.
}
或者
function dayAdvance ($startDay, $endDay, $weekType, $printed = array()) { ... }
注意:
array_push()
的更快替代方法是使用[]
将值简单地附加到数组中:$printed[] = $newdateform;
此方法将自动检测变量是否从未初始化,并在追加数据之前将其转换为数组(换句话说,没有错误)。
更新:
如果要让
$printed
的值保留在函数之外,则必须通过引用传递它或将其声明为global
。上面的示例等效于而不是。下面的示例等效于使用global
(实际上,比使用global
更好的做法是-迫使您更加谨慎地使用代码,防止意外的数据操作):function dayAdvance ($startDay, $endDay, $weekType, &$printed) { ... }
关于php - 警告: array_push() expects parameter 1 to be array,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12204713/