Using PHP to beautify JSON data

I'm currently working on generating JSON output for a specific JavaScript application, but I'm encountering a formatting issue that the script is not recognizing. Here's how I've structured my JSON so far:

// setting up the feed
$feed = [
    "mapwidth" => "800",
    "mapheight" => "600",
    "categories" => [],
    "levels" => [
        "id" => "canada",
        "title" => "Canada",
        "map" => "src/images/shops-map.svg",
        "locations"         => []
    ]
];

// fetching data from the database      
$locations = perch_collection('Shops', [
    'sort-order'    => 'DESC',
    'skip-template' => true,
    'count'         => 10,
]);

//looping 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"
        ];
    }
}

//generating the final JSON output
header('Content-Type: application/json');
echo json_encode($feed, JSON_PRETTY_PRINT);

Current 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"
            }
        ]
    }
}

Expected 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"
                }
            ]
        }
    ]
}

The concern arises when "levels": { is shown in the output instead of using square brackets followed by curly brackets as expected by the script. It appears to be an issue with handling arrays with only one item, causing frustration as I try to troubleshoot this dilemma.

Answer №1

To properly implement the additional array levels, you must make changes in two specific sections of the code...

"layers" => [[
    "id" => "france",
    "title" => "France",
    "map" => "src/images/shops-map.svg",
    "locations"         => []
]]

Additionally, remember to include locations within the designated level...

$feed['layers'][0]['locations'][]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

php using array_diff

I need help finding the difference between two arrays. $array1 = array(1,2,3,4); $array2 = array(1,2,3,4,5); $difference = array_diff($array1, $array2); print_r($difference); Why am I getting no output? Shouldn't the result be "5" included in th ...

Unable to retrieve object using ajax GET from the controller

I'm facing an issue where I am trying to send back an object in JSON format to my JavaScript code. However, when attempting to do so, the error event is being triggered with a parseerror message. What could be causing this problem? $.ajax({ url: ...

Exploring the Depths: A Guide to Selecting Nodes in Java Based on Depth

In my current JSON representation, I have the following structure: { "total": "555", "offset": "555", "hasMore": "false", "results": [ { "associations": { "workflowIds": [], "companyIds": [], "ownerIds": [], ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info->stock ...

Tips for organizing dynamic table data following an append operation

Hey there! I'm currently working on a project involving sorting students after applying filters. Once the students have been filtered, I need to append classes and text to buttons as shown in the image below: https://i.stack.imgur.com/c9Mtm.png The HT ...

Every time an input field is clicked, an email is sent

I'm struggling with the contact form on my website. Instead of sending an email after clicking on each input field, I want it to send only one email after hitting the submit button. Currently, it sends a total of 5 emails - 1 with user inputs and 4 wi ...

A ModelSerializer that is nested within another ModelSerializer

I'm currently working on setting up a nested JSON file in Django Rest Framework. I've been researching different approaches to properly nest my serializers, but haven't had much success. I'm struggling with creating a model serializer ...

Guide on transforming a JSON String into a Java object

When passing a JSON string from JSP to the server via AJAX call, I am converting it to a JSON object. How do I then convert this JSONObject into a model class object in Java? On the server side, I am doing the following: HttpServletRequest request = Ser ...

Rest assured, with Ajax Security, your protection is in good

I am currently developing a browser game that heavily utilizes AJAX instead of page refreshes. The combination of PHP and JavaScript is being employed for this project. However, during the course of my work, I became aware of the potential security vulnera ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

What is the best way to retrieve the dates for the current month as well as the following month

I have a php script that I need to modify in order to display the current month and the next month's dates using PHP. Below are the functions I am currently using for this purpose. html/php code (functions for current month and next month): <!-- D ...

Employing the date time difference when considering different time zones

I came across a helpful link earlier on the topic of calculating time differences in minutes, hours, and days: How to get time difference in minutes in PHP Here is an example I was experimenting with: $date1 = new DateTime('first day of this ...

How to Use jQuery Post Method to Submit a Form Without Redirecting

I am looking to enhance the user experience of my form by preventing it from reloading upon submission. Specifically, I want to trigger the call to index.php when the submit button named "delete-image" is clicked in the scenario outlined below. It's i ...

Converting SQL Select Queries into JSON for Organizing Menu Layout

I need assistance with a query that can generate JSON output for creating a menu structure. I want to populate the Menu using this JSON data. Below are the details of the two tables I am working with and the query I have tried so far: SELECT c.ID As ...

Flexible structure PHP API that supports requests and responses in JSON or XML format

I am currently in the process of developing a PHP API (web service) that will primarily involve retrieving lists of items. These items may have sub-objects with their own fields, or even nested objects. Since this API will be utilized by various projects, ...

Encountered an issue loading the file or assembly netwonsoft.json following recent updates to Visual Studio and NuGet

Recently, I updated Visual Studio to update 4 before updating all packages through NuGet. However, upon attempting to run my website, I encountered the following error: An exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Tips for eliminating a particular value using jQuery

Is there a way to remove specific data from an input text value using jQuery, but the code seems to be showing incorrect results? <input id="value1" type="hidden" name="value1" value="352880,350906,341563"> <script src="https://code.jquery.com/ ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...