I am taking CSV data and using PHP to generate JSON, but I'd like to know if it's possible to take certain rows from the CSV to create arrays within an object, see goal below for clarity:
I have the following example CSV data:
songId, title, artists:name[1], artists:main[1], artists:name[2], artists:main[2]
"trk-01", "Track 1", "artist 1", "true", "artist 2", "false"
"trk-02", "Track 2", "artist 3", "true", "artist 4", "false"
(This can be formatted to suit the solution)
The following PHP is being used to create JSON from the above CSV:
if (($handle = fopen('example.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
$completeobj = array("tracks" => $complete);
$result = array_merge($completeobj);
fclose($handle);
echo json_encode($result, JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($result, JSON_PRETTY_PRINT));
fclose($fp);
This is generating JSON that looks like:
{
"tracks": [
{
"songId": "trk-01",
"title": "Track 1",
"artists:name[1]": "artist 1",
"artists:main[1]": "true",
"artists:name[2]": "artist 2",
"artists:main[2]": "false"
},
{
"songId": "trk-02",
"title": "Track 2",
"artists:name[1]": "artist 3",
"artists:main[1]": "true",
"artists:name[2]": "artist 4",
"artists:main[2]": "false"
}
]
}
But my goal is to take those 'artists' rows in the CSV and put their values into an array within the object artists, see desired json below:
{
"tracks": [
{
"songId": "trk-01",
"title": "track 1",
"artists":
[
{
"name": "Artist 1",
"main": true
},
{
"name": "Artist 2",
"main": false
}
]
},
{
"songId": "trk-02",
"title": "track 2",
"artists":
[
{
"name": "Artist 3",
"main": true
},
{
"name": "Artist 4",
"main": false
}
]
}
]
}
If anyone could suggest a method of achieving this or show me an example that may help me to figure it out that would be ace!
array_combine, but just create the desired sub-array structure yourself in the while loop …?