首页 > 解决方案 > 使用 PHP 将 JSON 数组转换为 CSV

问题描述

我需要让 csv 具有第一张图片的格式,但我目前正在获得第二张图片作为最终结果,我该如何正确设置它以便 MailChimp 可以正确读取 csv

        $jsonDecoded = json_decode(file_get_contents('emails.json', true), true);   

        $list = array(
            array('Email Address', 'First Name')
        );

        $timestamp = time();
        foreach($jsonDecoded as $entry)
        {
            $new = array($entry['email'], $entry['name']);
            $list[$timestamp] = $new;
        }

        //if old file exist delete
        $fp = fopen('emails.csv', 'w');
        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }
        fclose($fp);

期望的输出 在此处输入图像描述

使用上述代码的电流输出

在此处输入图像描述

标签: phpcsv

解决方案


我可以看到的主要问题是您正在覆盖数组中的相同字段,因为您在循环中使用了相同的键

    //$timestamp = time(); - only set once, won't change
    foreach($jsonDecoded as $entry)
    {
        // this will update, but won't produce a different key for each iteration, 
        // because the loop might be faster than the smallest precision 
        // that the time() function can produce
        $timestamp = time();
                            
        $new = array($entry['email'], $entry['name']);
        $list[$timestamp] = $new;
    }

我没有看到时间戳本身的用途,所以我建议只使用array_push()或下面显示的速记

    foreach($jsonDecoded as $entry)
    {
        $new = array($entry['email'], $entry['name']);
        $list[] = $new; // this just adds the element to the end of the array
    }

推荐阅读