1

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?

1
  • you solved your own issue, as you said, you need commands to be an ARRAY or objects :) Commented Oct 4, 2017 at 3:00

3 Answers 3

4

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

If I understand it correctly, this should be the answer
2

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);

Comments

2

Here you go:

$arr["Commands"] = [
     ["StopCollection" => true],
     ["Send" => false],
     ["HeartbeatSend" => 60],
];
echo json_encode($arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.