1 回答
TA贡献1797条经验 获得超4个赞
如果您首先检查了所有元素并建立了所有字段的列表,那么您可以确保每一行都包含所有可能的元素。
然后它创建一个空模板数组,其中包含(使用array_fill_keys())中的所有键,并且对于每一行将填充存在的项目...
$array = json_decode($data, true);
// Scan all rows adding keys to list
$keys = [];
foreach ( $array['element_2'] as $row ) {
$keys = array_merge($keys, array_keys($row));
}
// Reduce to unique keys
$keys = array_unique($keys);
$handle = fopen("a.csv", "w");
// Write out keys as header
fputcsv($handle, $keys, ',');
// Create empty array with the keys
$template = array_fill_keys($keys, null);
foreach ($array['element_2'] as $key => $row) {
// Uses array_merge() to copy the values from the row to the template
fputcsv($handle, array_merge($template, $row));
}
fclose($handle);
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报