PHP 数组到 Json 对象

2022-08-30 22:44:23

我需要将PHP数组转换为JSON,但我没有得到我所期望的。我希望它是一个对象,我可以使用数字索引轻松导航。下面是一个示例代码:

$json = array();
$ip = "192.168.0.1";
$port = "2016";
array_push($json, ["ip" => $ip, "port" => $port]);
$json = json_encode($json, JSON_PRETTY_PRINT);
// ----- json_decode($json)["ip"] should be "192.168.0.1" ----
echo $json;

这就是我得到的

[  
   [  
      "ip" => "192.168.0.1",
      "port" => "2016"
   ]
]

但是我想得到一个对象而不是数组:

{  
   "0": {  
      "ip": "192.168.0.1",
      "port": "2016"
   }
}

答案 1

您想要 .json_encode($json, JSON_FORCE_OBJECT)

顾名思义,JSON_FORCE_OBJECT标志强制 json 输出是一个对象,即使它通常表示为数组。

您还可以消除对一些稍微干净的代码的使用:array_push

$json[] = ['ip' => $ip, 'port' => $port];

答案 2

只是只使用

$response=array();
$response["0"]=array("ip"     => "192.168.0.1",
                     "port"   => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);