且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 数组到 Json 对象

更新时间:2023-01-17 14:51:47

你想要json_encode($json, JSON_FORCE_OBJECT).

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

您还可以取消使用 array_push 以获得一些更简洁的代码:

$json[] = ['ip' =>$ip, '端口' =>$端口];

I need to convert a PHP array to JSON but I don't get what I expect. I want it to be an object that I can navigate easily with a numeric index. Here's an example code:

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

This is what I get

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

But I want to get an object instead of array:

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

You want to json_encode($json, JSON_FORCE_OBJECT).

The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.

You can also eliminate the use of array_push for some slightly cleaner code:

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