I am trying to create a JSON array through PHP in that format:
{
"Commands":[
{
"StopCollection":true
},
{
"Send":false
},
{
"HeartbeatSend":60
}
]
}
The closest I got to do that is:
by using JSON_FORCE_OBJECT
$commands = array();
$commands['Commands'] = array();
array_push($commands['Commands'],array('StopCollection' => true));
array_push($commands['Commands'],array('Send' => false));
array_push($commands['Commands'],array('HeartbeatSend' => 60));
$jsonCommands = json_encode($commands, JSON_FORCE_OBJECT);
Which outputs
{
"Commands":{
"0":{
"StopCollection":true
},
"1":{
"Send":false
},
"2":{
"HeartbeatSend":60
}
}
}
And using (object)
$commands = (object) [
'Commands' => [
'StopCollection' => true,
'Send' => false,
'HeartbeatSend' => 60
]
];
$jsonCommands = json_encode($commands);
Which outputs
{
"Commands":{
"StopCollection":true,
"Send":false,
"HeartbeatSend":60
}
}
Both are close but I need Commands to be an array of objects without a key. How do I do that?
asked Oct 4, 2017 at 2:53
Naguib Ihab
4,5368 gold badges53 silver badges86 bronze badges
-
you solved your own issue, as you said, you need commands to be an ARRAY or objects :)Ralph Thomas Hopper– Ralph Thomas Hopper2017年10月04日 03:00:56 +00:00Commented Oct 4, 2017 at 3:00
3 Answers 3
If you want to remove indexes from $commands Try,
json_encode( array_values($commands) );
Sign up to request clarification or add additional context in comments.
1 Comment
parpar
If I understand it correctly, this should be the answer
You can just do this
$commands = array(
'Commands' => array(
array('StopCollection' => true),
array('Send' => false),
array('HeartbeatSend' => 60)
)
);
$jsonCommands = json_encode($commands);
print_r($jsonCommands);
answered Oct 4, 2017 at 2:59
Agam Banga
2,6931 gold badge14 silver badges18 bronze badges
Comments
Here you go:
$arr["Commands"] = [
["StopCollection" => true],
["Send" => false],
["HeartbeatSend" => 60],
];
echo json_encode($arr);
answered Oct 4, 2017 at 3:10
CodeGodie
12.2k6 gold badges40 silver badges66 bronze badges
Comments
lang-php