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!
var_export(json_decode($json, true))~ eval.in/522922