php - 使用对象创建一个JSON数组

时间:2017-10-04 02:53:21

标签: php json

我试图通过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成为没有键的对象数组。我该怎么做?

3 个答案:

答案 0 :(得分:4)

如果要从$命令中删除索引,请尝试

json_encode( array_values($commands) );

答案 1 :(得分:2)

你可以这样做

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

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

答案 2 :(得分:2)

你走了:

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