michaelmcgurk michaelmcgurk - 1 month ago 6
PHP Question

Reformat JSON array using PHP

I have a small PHP script that pulls in a CSV file and creates a JSON array from this.

However, I'd like to change the formatting of my outputted JSON array.

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);
?>


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


 

How do I transform my CSV into the following:

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


So it basically merges the first 2 items and adds
name
&
location
.

 

My
food.csv
file is:

McDonalds,Fast Food,London
Marios,Italian,Manchester

Answer

Next time please try something by yourself:

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

Output

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

You need to create a new array in the desired format, and simple json_encode it.

Comments