You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:20:31