简体   繁体   中英

php - Create a JSON array with objects

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?

如果要从$ commands Try中删除索引,

json_encode( array_values($commands) );

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

Here you go:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM