PHP覆盖写入CSV文件时跳过首行功能失效问题求助
问题原因
你的continue逻辑不生效源于两个错误:
- 行计数变量
$rows放在foreach循环内部初始化,每次遍历元素都会被重置为0,$rows == 1的判断条件永远不会触发 - 若要跳过第一次循环写入,判断阈值应为
$rows == 0,计数默认从0开始累加
正确实现方案
方案1:先写自定义表头再写数据(推荐)
不需要跳过任何循环,打开文件后先写入表头再循环写入业务数据即可,逻辑最清晰:
$result =[]; // 第一步:先写入自定义表头,替换为你需要的字段即可 $customHeader = ['日期', '名称', '总处理量', '效率占比']; fputcsv($out, $customHeader); // 第二步:循环写入业务数据 foreach($sumArray as $key => $totalItems) { $result[$totalItems][] = $sumArray1[$key]; $timeNeeded = implode(" ", $result[$totalItems]); list($id1, $name1) = explode('_', $key); $procenti = round(($perMin*$totalItems)/($timeNeeded/$precentEff),2); $procentiCon = $procenti . " %"; $pickingEffRes = [$name1 , $totalItems, $procentiCon]; fputcsv($out, $pickingEffRes); }
方案2:确实需要跳过第一次循环写入的实现
如果你的场景必须空出第一行后续再补表头,用以下写法:
$result =[]; $rows = 0; // 计数变量放在循环外部初始化 foreach($sumArray as $key => $totalItems) { $result[$totalItems][] = $sumArray1[$key]; $timeNeeded = implode(" ", $result[$totalItems]); list($id1, $name1) = explode('_', $key); $procenti = round(($perMin*$totalItems)/($timeNeeded/$precentEff),2); $procentiCon = $procenti . " %"; $pickingEffRes = [$name1 , $totalItems, $procentiCon]; // 跳过第一次循环的写入操作 if($rows == 0) { $rows++; continue; } fputcsv($out, $pickingEffRes); $rows++; }
内容的提问来源于stack exchange,提问作者stoperan
相关产品推荐
相关产品推荐

