Reputation: 27
I want to write an "nested" JSON structure with PHP Have a look below how the result should look like:
(Manually written -can read in JS without errors :) )
{
"general": {
"language": "English",
"workingmode": "Normal"
},
"scene": [{
"id": 0,
"calendar_event": "urlaub",
"element": [
{
"device": "boiler1",
"active_state": "nothing",
"hybernation_state": "off",
"calendar_name": "roomlink4"
},
{
"device": "boiler1",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}
]
},
{
"id": 1,
"calendar_event": "urlaub",
"element": [
{
"device": "boiler1",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
},
{
"device": "boiler1",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}
]
}
]
}
This is the code I have so far:
$knxGenSet = (object) [
'general' => (object) [],
'scene' => []
//Now i Struggle with this part, i cannot accomplish it to add "element" so that it is nested inside of "scene"
];
//creating structure for "general"
$knxGenSet->general->language = $_POST["langsetts"];
$knxGenSet->general->workingmode = $_POST["wmodesetts"];
//second part which i struggle with
$knxGenSet->scene[] = (object) [
//creating structure for "scene"
'id' => 0,
'calendar_event' => "anything"
//Struggle: cannot get it right to add "element"-array which consists of 4 more String to the structure
];
I did manage to add the "general" tab and an part of "scene" but what i didn't manage to do is to add the part of "element"-array to the "scene"
btw i can allready read this json format with JS
Thanks in advance (kind of newb on json territory! :()
Upvotes: 0
Views: 36
Reputation: 2321
you were missing some minor key points
$knxGenSet = (object) [
'general' => (object) ["language" => $_POST["langsetts"],
"workingmode" => $_POST["wmodesetts"]
]
];
for($j=0; $j<2; $j++) {
$scene = (object) [
'id' => $j,
'calendar_event' => $_POST["calendarevent" . $j]
];
for($ii=0; $ii<2; $ii++) {
$scene->element[] = (object) [
"device" => "boiler".$ii,
"active_state"=> "on",
"hybernation_state"=> "off",
"calendar_name"=> "roomlink4"
];
}
$knxGenSet->scene[] = $scene;
}
print json_encode($knxGenSet);
output
{
"general": {
"language": null,
"workingmode": null
},
"scene": [{
"id": 0,
"calendar_event": null,
"element": [{
"device": "boiler0",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}, {
"device": "boiler1",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}]
}, {
"id": 1,
"calendar_event": null,
"element": [{
"device": "boiler0",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}, {
"device": "boiler1",
"active_state": "on",
"hybernation_state": "off",
"calendar_name": "roomlink4"
}]
}]
}
Upvotes: 1