本文将介绍php中常用的几个json转数组函数。
json_decode()json_decode()函数是php中用于将json字符串转换成php数组或对象的基本函数。它的语法如下:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
其中:
$json:需要转换的json字符串。$assoc:如果该参数为true,则返回数组;如果为false,则返回object对象。$depth:指定最大深度,用于控制递归调用的深度。默认值为512。$options:json编码选项,可以指定转换后的格式。示例代码:
$json_str = '{name:tom,age:20,hobby:[reading,writing]}';$arr = json_decode($json_str, true);print_r($arr);
输出结果:
array( [name] => tom [age] => 20 [hobby] => array ( [0] => reading [1] => writing ))
通过json_decode()函数,我们成功将json字符串转换为了数组。
json_decode()与json_throw_on_error结合使用在php 7.3及以上版本中,我们可以使用json_throw_on_error选项,让json_decode()函数在转换出错时抛出异常。示例代码如下:
$json_str = '{name:tom,age:20,hobby:[reading,writing]}';try { $arr = json_decode($json_str, true, 512, json_throw_on_error); print_r($arr);} catch (jsonexception $e) { echo 'json错误:' . $e->getmessage();}
输出结果:
json错误:syntax error
在本例中,由于json字符串格式有误,json_decode()函数抛出了异常,并提示了错误信息。
json_last_error_msg()在使用json_decode()函数转换json字符串时,有时会存在解析错误,此时我们可以使用json_last_error_msg()函数获取错误信息。示例代码如下:
$json_str = '{name:tom,age:20,hobby:[reading,writing';$arr = json_decode($json_str, true);if (json_last_error() === json_error_none) { print_r($arr);} else { echo 'json错误:' . json_last_error_msg();}
输出结果:
json错误:syntax error
在本例中,由于字符串格式错误,json_last_error_msg()返回了错误信息。
json_encode()在php中,我们也可以将php数组转换为json格式字符串,这需要使用json_encode()函数。它的语法如下:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
其中:
$value:需要转换为json格式的php变量。$options:可选。json 编码选项。$depth:可选。指定最大深度。默认值为512。示例代码如下:
$arr = array('name' => 'tom', 'age' => 20, 'hobby' => array('reading', 'writing'));$json_str = json_encode($arr, json_unescaped_unicode);echo $json_str;
输出结果:
{name:tom,age:20,hobby:[reading,writing]}
通过json_encode()函数,我们成功将php数组转换为了json字符串。
总结:
在php中,我们可以使用json_decode()函数将json字符串转换为数组或对象,还可以使用json_encode()函数将php数组转换为json格式的字符串。一般情况下,使用默认选项即可,若有需要,可以使用相关选项来进行配置。在解析或编码json时,我们也可以使用相关函数获取错误信息,以便更好地进行处理。
以上就是php json转数组函数的详细内容。
