php-使用对象创建JSON数组

php-使用对象创建JSON数组,php,json,Php,Json,我正在尝试通过PHP以该格式创建JSON数组: { "Commands":[ { "StopCollection":true }, { "Send":false }, { "HeartbeatSend":60 } ] } 我能做的最接近的事情是: 通过使用JSON_FORCE_对象 哪个输出 { "Commands":{ "0":{

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

{
   "Commands":[
      {
         "StopCollection":true
      },
      {
         "Send":false
      },
      {
         "HeartbeatSend":60
      }
   ]
}
我能做的最接近的事情是: 通过使用JSON_FORCE_对象

哪个输出

{
   "Commands":{
      "0":{
         "StopCollection":true
      },
      "1":{
         "Send":false
      },
      "2":{
         "HeartbeatSend":60
      }
   }
}
{
   "Commands":{
      "StopCollection":true,
      "Send":false,
      "HeartbeatSend":60
   }
}
和使用对象

哪个输出

{
   "Commands":{
      "0":{
         "StopCollection":true
      },
      "1":{
         "Send":false
      },
      "2":{
         "HeartbeatSend":60
      }
   }
}
{
   "Commands":{
      "StopCollection":true,
      "Send":false,
      "HeartbeatSend":60
   }
}
两者都很接近,但我需要命令成为一个没有键的对象数组。我该怎么做呢?

你可以这样做

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

$jsonCommands = json_encode($commands);
print_r($jsonCommands);
你可以这么做

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

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

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

json_encode( array_values($commands) );

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

json_encode( array_values($commands) );
给你:

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

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

你解决了你自己的问题,正如你所说,你需要命令成为数组或对象:你解决了你自己的问题,正如你所说,你需要命令成为数组或对象:如果我理解正确,这应该是答案如果我理解正确,这应该是答案