使用PHP重新格式化JSON数组

时间:2016-10-11 14:26:10

标签: php jquery json csv

我有一个小的PHP脚本,可以输入CSV文件并从中创建一个JSON数组。

但是,我想更改输出的JSON数组的格式。

PHP:

<?php
$file = fopen('food.csv', 'r');
$allfile = [];
$idsColumnsWanted = array_flip([0, 1, 2]);
while (false !== $fields = fgetcsv($file)) {
    $allfile[] = array_intersect_key($fields, $idsColumnsWanted);
}
fclose($file);
?>

输出: var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];

如何将CSV转换为以下内容:

var data = [
{name:"McDonald's Fast Food",location:"London"},
{name:"Marios Italian",location:"Manchester"}
];

所以它基本上合并了前两个项目并添加了name&amp; location

我的food.csv文件是:

McDonalds,Fast Food,London
Marios,Italian,Manchester

3 个答案:

答案 0 :(得分:0)

下次请亲自尝试一下:

$data = [["McDonalds", "Fast Food", "London"], ["Marios", "Italian", "Manchester"]];
$newData = [];
foreach ($data as $info) {
    $newData[] = [
        'name' => $info[0] . " " . $info[1],
        'location' => $info[2]
    ];
}
var_dump(json_encode($newData));

<强>输出

string '[{"name":"McDonalds Fast Food","location":"London"},{"name":"Marios Italian","location":"Manchester"}]' (length=104)

您需要以所需的格式创建一个新数组,并简单json_encode

答案 1 :(得分:0)

如果你考虑使用jQuery - 那就是

var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];

var formated_data = {};

$.each(data, function(key, val) {
    formated_data[key] = {name: val[0] + ' ' + val[1], location: val[2]}
});

console.log(formated_data);

答案 2 :(得分:-1)

打开CSV文件,然后将CSV解析为数组。 流这一行,

    <?php 
     $file="1_23.csv";
     $csv= file_get_contents($file);
     $array = array_map("str_getcsv", explode("\n", $csv));
     $json = json_encode($array);
     print_r($json);
    ?>