I am trying to build some JSON output for a JavaScript application and it's expecting the format in a very specific way.
At the moment I have successfully generated a JSON output from my php file. The problem I have is around how the use of brackets differs from what the script expects. Here is how I built the JSON:
// define my feed
$feed = [
"mapwidth" => "800",
"mapheight" => "600",
"categories" => [],
"levels" => [
"id" => "canada",
"title" => "Canada",
"map" => "src/images/shops-map.svg",
"locations" => []
]
];
// grab our items from the database
$locations = perch_collection('Shops', [
'sort-order' => 'DESC',
'skip-template' => true,
'count' => 10,
]);
//loop through the items
if (count($locations)) {
foreach($locations as $location) {
$feed['levels']['locations'][] = (object)[
'id' => $location['id'],
'title' => $location['name'],
'about' => $location['info'],
"description" => $location['info'],
"category" => "clothing",
"thumbnail" => $location['image'],
"x" => "0.3781",
"y" => "0.4296"
];
}
}
//ready to generate
header('Content-Type: application/json');
echo json_encode($feed, JSON_PRETTY_PRINT);
My output:
{
"mapwidth": "800",
"mapheight": "600",
"categories": [],
"levels": {
"id": "canada",
"title": "Canada",
"map": "src\/images\/shops-map.svg",
"locations": [
{
"id": "u-001",
"title": "Test Shop",
"about": "sdf sdfsd fsd fsdfdsf sd fsddsfsdf sdfsdfdsfsdf",
"description": "sdf sdfsd fsd fsdfdsf sd fsddsfsdf sdfsdfdsfsdf",
"category": "clothing",
"thumbnail": null,
"x": "0.3781",
"y": "0.4296"
}
]
}
}
Desired output:
{
"mapwidth": "800",
"mapheight": "600",
"categories": [],
"levels": [
{
"id": "canada",
"title": "Canada",
"map": "src\/images\/shops-map.svg",
"locations": [
{
"id": "u-001",
"title": "Test Shop",
"about": "sdf sdfsd fsd fsdfdsf sd fsddsfsdf sdfsdfdsfsdf",
"description": "sdf sdfsd fsd fsdfdsf sd fsddsfsdf sdfsdfdsfsdf",
"category": "clothing",
"thumbnail": null,
"x": "0.3781",
"y": "0.4296"
}
]
}
]
}
Note where "levels": { is output. My script expects to see the square brackets followed by the curly brackets. I'm losing my mind on this. I think it's how it's handling an array if there is only one item, although that has not led me to a solution as of yet.
$feed['levels'] = [['id' => ... ]]