使用array_push操作多维数组报错:参数1应为数组,实际为null
解决array_push()参数为null的多维数组问题
嘿,我来帮你搞定这个报错!你遇到的array_push() expects parameter 1 to be array, null given问题,根源很简单:当你用$i跟踪索引时,只有初始的$days[0]被初始化成了数组,当$i递增到1、2之后,$days[$i]还没被定义,默认是null,array_push自然找不到有效的数组来操作啦。
我给你几个可行的解决方案,还顺便优化了代码结构:
方案1:提前初始化当前索引的数组
在每次循环开始时,先把$days[$i]初始化为空数组,这样后续的array_push就有明确的数组可以操作了:
$days = []; $i = 0; foreach($recurring_appt as $rec){ // 先初始化当前索引对应的空数组 $days[$i] = []; $check = str_split($rec->frequency_data); if($check[0] == 'x'){ array_push($days[$i], 'sunday');} if($check[1] == 'x'){ array_push($days[$i],'monday');} if($check[2] == 'x'){ array_push($days[$i],'tuesday');} if($check[3] == 'x'){ array_push($days[$i], 'wednesday');} if($check[4] == 'x'){ array_push($days[$i], 'thursday');} if($check[5] == 'x'){ array_push($days[$i],'friday');} if($check[6] == 'x'){ array_push($days[$i], 'saturday');} $i++; }
方案2:放弃手动索引,直接push子数组
其实完全不用手动维护$i这个变量,每次循环生成一个子数组,直接把它push到$days里就行,代码更简洁:
$days = []; foreach($recurring_appt as $rec){ $currentDays = []; $check = str_split($rec->frequency_data); if($check[0] == 'x'){ $currentDays[] = 'sunday';} if($check[1] == 'x'){ $currentDays[] = 'monday';} if($check[2] == 'x'){ $currentDays[] = 'tuesday';} if($check[3] == 'x'){ $currentDays[] = 'wednesday';} if($check[4] == 'x'){ $currentDays[] = 'thursday';} if($check[5] == 'x'){ $currentDays[] = 'friday';} if($check[6] == 'x'){ $currentDays[] = 'saturday';} $days[] = $currentDays; }
进阶优化:减少重复代码
你还可以把星期几做成一个映射数组,用循环替代重复的if判断,这样代码更易维护:
$days = []; // 按索引对应星期几,和frequency_data的字符顺序一致 $weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; foreach($recurring_appt as $rec){ $currentDays = []; $check = str_split($rec->frequency_data); foreach($check as $index => $flag){ if($flag == 'x'){ $currentDays[] = $weekDays[$index]; } } $days[] = $currentDays; }
这样修改后,不仅解决了报错问题,后续要调整星期的顺序或者名称,只需要修改$weekDays数组就行,不用改一堆if判断。
内容的提问来源于stack exchange,提问作者Koby Campbell
相关产品推荐
相关产品推荐

