- 将获取到的JSON字符串转换为PHP对象或数组
注:使用PHP的 json_decode(string $json, bool $assoc) 函数,其中assoc参数默认为false,返回PHP对象,为true时返回PHP数组,如果入参的JSON字符串无法解析或数据深度超过递归限制,返回NULL
$json_string = '{"Baidu":3,"Ali":1,"Tencent":2}'; //JSON字符串
$php_obj = json_decode($json_string); //转换为PHP对象
var_dump($php_obj);
$php_arr = json_decode($json_string,true); //转换为PHP数组
var_dump($php_arr);
$tmp1 = $php_obj->ali; //获取PHP对象属性
$tmp2 = $php_arr["ali"]; //获取PHP数组值
查看转换后的类型
object(stdClass)#1 (3) { ["Baidu"]=> int(3) ["Ali"]=> int(1) ["Tencent"]=> int(2) }
array(3) { ["Baidu"]=> int(3) ["Ali"]=> int(1) ["Tencent"]=> int(2) }
- 将PHP对象或数组转换为JSON字符串
注:使用PHP的 json_encode(mixed $value) 函数,成功时返回JSON编码的字符串,失败时返回false
$php_arr = array("Baidu"=>3,"Ali"=>1,"Tencent"=>2); //PHP键值数组
$json_string = json_encode($php_arr); //转换为JSON字符串
var_dump($json_string);
查看转换后的类型
string(32) "{"Baidu":3,"Ali":1,"Tencent":2}" //JSON格式字符串