下面的php提取我的csv文件并输出到JSON文件。
<?php
echo "<h2>Uploading....</h2>";
$fh = fopen("assets/files/locationsCSV.csv", "r");
$csvData = array();
while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
$csvData[] = $row;
}
// echo json_encode($csvData);
file_put_contents("assets/files/locationsCSV.json",json_encode($csvData))
?>
我的json文件中的JSON如下所示:当前输出:
["Zipcode","City","Primary State","SS","County"], # only prints once
["24553","","Virginia","49050","Appomattox"], # then just this
["24553","","Virginia","49140","Buckingham"], # etc
如何获取这样的输出/使用邮政编码列作为对象标题重新格式化?
所需的JSON输出:
{
ZipCode: 24553, {
City: ,
Primary State: Virginia,
SS: 49050,
County: Appomattox
}
答案 0 :(得分:1)
您需要将CSV文件的第一行读取到keys数组中,并将这些键与循环中的每一行数据结合起来:
$csvData = array();
$keys = fgetcsv($fh, 0, ",");
while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
$csvData[] = array_combine($keys, $row);
}