php json格式转换的方法:1、通过json_encode函数将php的array和object转换成json格式;2、通过json_decode函数将json文本转换为相应的PHP数据结构。
本文操作环境:windows7系统、PHP7.1版,DELL G3电脑。
php json格式互转
php原生提供 json_encode($str)和json_decode($str)。
1.json_encode()
此函数是将php的array和object转换成json格式。
eg:array $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); result:{"a":1,"b":2,"c":3,"d":4,"e":5} eg:object $obj->body = 'another post'; $obj->id = 21; result: { "body":"another post", "id":21, }
二、索引数组和关联数组
PHP支持两种数组,一种是只保存"值"(value)的索引数组(indexed array),另一种是保存"名值对"(name/value)的关联数组(associative array)。
由于javascript不支持关联数组,所以json_encode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。
比如,现在有一个索引数组
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
结果为:
["one","two","three"]
如果将它改为关联数组:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
结果就变了:
{"1":"one","2":"two","3":"three"}
注意,数据格式从"[]
来源gaodai.ma#com搞#代!码网
"(数组)变成了"{}"(对象)。
如果你需要将"索引数组"强制转化成"对象",可以这样写