php - 使用 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);
使用上述代码的电流输出
解决方案
我可以看到的主要问题是您正在覆盖数组中的相同字段,因为您在循环中使用了相同的键
//$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
}
推荐阅读
- python - 解析值具有“&”的查询字符串
- ios - 在 Firebase iOS 中刷新身份验证令牌时出错
- c# - 当我触发插入查询时,抛出异常:System.Data.dll 中的“System.Data.SqlClient.SqlException”
- performance - 当它说 L1 缓存参考或主内存参考时是什么参考
- jquery - jQuery替换元素中的字符串会破坏内容
- assembly - MIPS跳转指令编码:为什么要左移,为什么要保留PC的高4位?
- android-studio - 在 Android Studio 的 ViewPager 中打开一个新片段
- javascript - 将数据库记录建模为 javascript 类对象的最佳实践是什么?
- c# - Assembly.LoadFile 在同一个程序集上引发程序集解析事件
- flutter - 未处理的异常:DioError [DioErrorType.DEFAULT]:将对象转换为可编码对象失败