PHP如何为数组中缺失的月份填充type值为0的对应元素
原有代码的错误点
array_search返回值判断错误:当匹配到的月份在原数组的索引为0时,弱类型判断if ($teste)会把0识别为假值,走入错误分支,需要用!== false做严格判断- 字段名拼写错误:你代码里写的
moth存在拼写错误和多余空格,正确字段名是month - 匹配到已有月份时,type值被硬编码为2,没有读取原数组中对应的实际type值
- 结果数组的索引赋值逻辑错误,使用
$res[$teste]赋值会打乱最终数组的顺序,直接顺序追加即可
修正后可直接运行的代码
第一种是优化后的写法,提前构建月份和type的映射,查找效率更高:
// 先把原数组转成「月份=>type」的映射 $monthMap = []; foreach ($d as $item) { $monthMap[$item['month']] = $item['type']; } $res = []; foreach ($allmonths as $month) { $res[] = [ 'type' => isset($monthMap[$month]) ? $monthMap[$month] : 0, 'month' => $month ]; } // 打印验证结果 print_r($res);
如果要基于你原有代码的逻辑最小改动,也可以改成下面这样:
$res = []; $months = array_column($d, 'month'); // 提前提取月份数组,避免循环中重复计算 foreach ($allmonths as $key => $mes) { $teste = array_search($mes, $months); if ($teste !== false) { // 严格判断是否匹配到 $res[] = ['type' => $d[$teste]['type'], 'month'=> $mes]; // 取原数组的type值,修正字段名 } else { $res[] = ['type' => 0,'month'=> $mes]; } }
两种写法运行后都能得到你给出的预期结果。
内容的提问来源于stack exchange,提问作者Taffarel Xavier
相关产品推荐
相关产品推荐

