PHP中将含嵌套数组的JSON转CSV,如何展开Schedule字段?
解决PHP嵌套数组转CSV独立列的问题
当前代码写入CSV时,嵌套的Schedule数组会被输出为字符串"Array",需要将其下的7个子数组转换为startHour-stopHour格式并作为独立列写入CSV,修改后的代码如下:
foreach(json_decode($result[$k], true) as $item) { // 格式化Schedule子数组为指定字符串格式 $formattedSchedule = []; foreach ($item['Schedule'] as $timeSlot) { $formattedSchedule[] = "{$timeSlot['startHour']}-{$timeSlot['stopHour']}"; } // 移除原数组中的Schedule字段,避免写入"Array" unset($item['Schedule']); // 合并原字段与格式化后的Schedule项,组成CSV行数据 $csvRow = array_merge($item, $formattedSchedule); // 写入CSV文件 fputcsv($fp, $csvRow); }
关键说明:
- 修正
json_decode的第二个参数:原代码使用字符串"true",应改为布尔值true,确保返回关联数组而非对象 - 遍历
Schedule子数组,将每个startHour和stopHour拼接为xx:xx-xx:xx格式的字符串 - 通过
unset移除原数组中的Schedule键,避免fputcsv将数组转为"Array"字符串 - 用
array_merge将原数据字段与格式化后的Schedule项合并,保证每个时间区间作为独立列输出
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

