user3745171
user3745171

Reputation: 33

How do I create JSON output in php using the defined format

I'm supposed to create a JSON output using a php script. The JSON format is predefined so I can't change it. Here's what it's supposed to look like..

{
"header": "My header",
"pages": [{
    "id": 1,
    "items": [{
        "header": "My first page",
        "text": "This is my first page"
    }, {
        "header": "My second page",
        "text": "This is my second page"
    }]
  }]
}

I have no problems creating the header object, nor the items array. The problem is that I'm not able to create pages as an array and the id object in it. The pages array will consist of more "pages", but I'm only listing one in the snippet below, hence I need to be an array.

The closest solution I've found is the following..

obj = new stdClass();
$obj->header = "My header";
$obj->pages = array();
$obj->pages["items"][] = array("header" => "My first page", "text" => "This is my first page");
$obj->pages["items"][] = array("header" => "My second page", "text" => "This is my second page");
echo json_encode($obj);

This results in..

{
"header":"My header",
"pages":{
    "items":[{
        "header":"My first page",
        "text":"This is my first page"
    }, {
        "header":"My second page",
        "text":"This is my second page"
    }]
  }
}

As you can see, there are two parts missing here..

The first thing is that pages should be an array, i.e. I'm missing the [ and ] brackets. The second problem is the missing "id": 1 object in the pages array which I can't figure out how to add.

Would really appreciate a code sample solving these two problems!

Upvotes: 0

Views: 1606

Answers (2)

Budianto IP
Budianto IP

Reputation: 1297

Try this one, just create an empty php file, and paste my code, I have tested it to match yours :

<?php
    $items = array();
    $pages = array();
    $items[] = array("header" => "My first page", "text" => "This is my first page");
    $items[] = array("header" => "My second page", "text" => "This is my second page");
    $pages[] = array("id" => 1, "items" => $items);
    $obj = array("header" => "My header", "pages" => $pages);
    echo json_encode($obj);
?>

Upvotes: 0

Moak
Moak

Reputation: 12885

It's easy if you replace all { with [, and : with =>, then you'll have php that represents your target json

$json = [
    "header" => "My header",
    "pages" => [
        [
            "id" => 1,
            "items" => [
                [
                    "header" => "My first page",
                    "text" => "This is my first page",
                ], [
                    "header" => "My second page",
                    "text" => "This is my second page",
                ],
            ],
        ],
    ],
];
echo json_encode($json);

from that point on you can extract the and replace the parts you want with variables.

Upvotes: 2

Related Questions