1.使用php内置函数json_encode()
php提供了一个内置函数json_encode()用来将php数组转换为json对象。json_encode()函数接受一个php变量作为参数,并将该变量编码为json格式的字符串。下面是使用json_encode()函数将php数组转换成json对象的例子。
$my_array = [1, 2, 'hello', 'world']; $json_string = json_encode($my_array); echo $json_string;
上面的代码输出结果如下:
[1,2,hello,world]
需要注意的是,json_encode()函数的第二个可选参数$option默认是0,表示输出结果中没有缩进。可以通过将这个参数设置为json_pretty_print来使结果更易读。
2.使用php内置函数json_decode()
与json_encode()函数对应,php还提供了json_decode()函数,用于将json格式的字符串转化为php数组,下面是使用json_decode()函数将json对象转换为php数组的例子。
$json_string = '[1,2,hello,world]'; $my_array = json_decode($json_string); var_dump($my_array);
输出结果为:
array(4) { [0]=> int(1) [1]=> int(2) [2]=> string(5) hello [3]=> string(5) world }
需要注意的是,json_decode()函数默认将json字符串转换为stdclass对象。如果你想将其转换为一个php数组的话,可以将json_decode()函数的第二个参数设置为true,如下所示:
$json_string = '{name: tom, age: 18}'; $my_array = json_decode($json_string, true); var_dump($my_array);
输出结果为:
array(2) { [name]=> string(3) tom [age]=> int(18) }
3.使用php类库
如果要对json数据进行更高级的编辑操作,可以使用php中的json类库,例如pecl-json或jsonlint。这些类库提供了比json_encode()和json_decode()函数更多的选项和功能。
例如,使用pecl-json类库,可以很方便地将php数组转换为json对象:
use \jsonserializable; class myarray implements jsonserializable{ private $arr; public function __construct($arr = []) { $this->arr = $arr; } public function jsonserialize() { return $this->arr; }} $my_array = new myarray([1, 2, 'hello', 'world']); $json_string = json_encode($my_array); echo $json_string;
输出结果为:
[1,2,hello,world]
需要注意的是,在将php对象转换为json对象时,必须让这个php对象实现jsonserializable接口。在实现jsonserializable接口后,json_encode()函数将调用接口方法jsonserialize()从而将php对象转换为json对象。
conclusion
本文介绍了如何在php中将数组转换为json对象。通过使用php内置函数json_encode()和json_decode(),我们可以方便地进行基础数据格式的转换。如果需要进行更高级的json数据编辑操作,可以使用php中的json类库。重新看一下我们的例子,不使用其他类库,可以这样来进行数组与json的互相转换:
$my_array = [1, 2, 'hello', 'world'];$json_string = json_encode($my_array);$result_array = json_decode($json_string, true);
如此简单,如此方便!
以上就是php 数组怎么转成json对象的详细内容。
