繁体   English   中英

php-使用对象创建JSON数组

[英]php - Create a JSON array with objects

我正在尝试通过PHP以这种格式创建JSON数组:

{
   "Commands":[
      {
         "StopCollection":true
      },
      {
         "Send":false
      },
      {
         "HeartbeatSend":60
      }
   ]
}

我要做的最接近的是:通过使用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);

哪个输出

{
   "Commands":{
      "0":{
         "StopCollection":true
      },
      "1":{
         "Send":false
      },
      "2":{
         "HeartbeatSend":60
      }
   }
}

并使用(object)

  $commands = (object) [
    'Commands' => [
      'StopCollection' => true,
      'Send' => false,
      'HeartbeatSend' => 60
    ]
  ];

  $jsonCommands = json_encode($commands);

哪个输出

{
   "Commands":{
      "StopCollection":true,
      "Send":false,
      "HeartbeatSend":60
   }
}

两者都很接近,但我需要Commands是没有键的对象数组。 我怎么做?

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

json_encode( array_values($commands) );

你可以这样做

$commands = array(
    'Commands' => array(
      array('StopCollection' => true),
      array('Send' => false),
      array('HeartbeatSend' => 60)
    )
  );

$jsonCommands = json_encode($commands);
print_r($jsonCommands);

干得好:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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