PHP 数组到 Json 对象 [英] PHP Array to Json Object

查看:43
本文介绍了PHP 数组到 Json 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 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"] 应该是192.168.0.1";----回声 $json;

这是我得到的

<预><代码>[[ip"=>192.168.0.1",端口"=>《2016》]]

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

<代码>{0":{ip":192.168.0.1",端口":2016"}}

解决方案

你想要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];

这篇关于PHP 数组到 Json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆