使用PHP将JSON数组转换为CSV
我需要让csv具有第一张图片的格式,但我目前得到的是第二张图片作为最终结果,我如何正确设置它,以便MailChimp可以正确读取csv使用PHP将JSON数组转换为CSV,php,csv,Php,Csv,我需要让csv具有第一张图片的格式,但我目前得到的是第二张图片作为最终结果,我如何正确设置它,以便MailChimp可以正确读取csv $jsonDecoded = json_decode(file_get_contents('emails.json', true), true); $list = array( array('Email Address', 'First Name') ); $tim
$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);
所需输出
具有上述代码的电流输出
我看到的主要问题是,您正在覆盖数组中的同一字段,因为您在循环中使用的是同一个键
//$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\u push()
或下面显示的速记
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[] = $new; // this just adds the element to the end of the array
}