json转换数据后面参数要带ture,代码
强大的PHP已经提供了内置函数:json_encode() 和 json_decode()。很容易理解,json_encode()就是将PHP数组转换成Json。相反,json_decode()就是将Json转换成PHP数组。
例如,代码如下:
$array = array("name" => "Eric","age" => 23);
echo json_encode($array);
程序将打印出:
{“name”:”Eric”,”age”:23}
再看下面的例子:
$array = array(0 => "Eric", 1 => 23);
echo json_encode($array); 程序将打印出 :["Eric",23]
以上两个例子可以看出,如果PHP数组的键都是数字,那么json_encode()返回一个数组形式的Json,如果PHP数组的键全是字符串,那么json_encode()就会返回一个对象形式的Json,刚已经说过,两者在js中的调用是不同的.
事实上,只要在PHP数组的键中有一个字符串形式的键,那么json_encode()就会返回对象形式的Json,这是不正确的,因为,虽然在PHP代码中不会出现错误,但要是将这样的Json传给JS函数,JS会将此Json当做一个对象,而对象是不可能以数字作为属性名的,也就是说JS 不知道这是什么:user.0.username(中间是数字零).
例子,代码如下:
$json_arr = array('WebName'=>'PHP网站开发教程网','WebSite'=>'http://www.php-z.com');
$php_json = json_encode($json_arr); //把php数组格式转换成 json 格式的数据
echo $php_json;
$php_json = json_decode($php_json); //再把json格式的数据转换成php数组
print_r($php_json);
json数组
$json = '[{"id":"22","name":"33","descn":"44"}]'; //json格式的数组转换成 php的数组
$arr = (Array)json_decode($json);
echo $arr[0]->id; //用对象的方式访问
json转换数据后面参数要带ture,代码如下:
$a = <<<EOD
{
"scoreInfo": {
"isB2cSeller": true,
"noMark": false,
"merchandisScore": "5.0",
"merchandisTotal": 1,
"width": 100
},
"rateListInfo": {
"watershed": 100,
"paginator": { "beginIndex": 1, "endIndex": 1, "firstPage": 1, "items": 1, "itemsPerPage": 8, "lastPage": 1, "length": 1, "offset": 0, "page": 1, "pages": 1
},
"rateList": [ { "aliMallSeller": false, "anony": true, "auctionSku": "颜色分类:蓝+黑;尺码:36", "award": "", "b2CSeller": false, "dispalyRateLevel1": 0, "dispalyRateLevel2": 0, "dispalyRateSum": 0, "displayRatePic": "", "displayUserLink": "http://i.taobao.com/u/MTExNTE1Mjk5MQ==/tlive/taodan_list.htm?from=rate", "displayUserNick": "l***1", "displayUserNumId": 0, "displayUserRateLink": "http://rate.taobao.com/rate.htm?user_id=0&rater=1", "displayUserSeller": false, "fee dAppendedDO": null, "fromB2cMapping": false, "fromMall": false, "fromOnePai": false, "fromVirtualHurling": false, "gapDates": 0, "id": 63810867055, "rateContent":288104151 "卖家的服务态度真好,你家的鞋子更是超值,5分,还要在买别的款。", "rateDate": "2013.04.14 16:50:11", "rateResult": 1, "ratedUserNumId": 361988210, "reply": "", "shareInfo": null, "tag": "", "tradeClosingdate": null, "type": 0, "userVipLevel": 0 }
],
"showMore": 0
},
"babyRateJsonList": "uri: /detailRate.vm cacheTime: 2013-04-26 22:07:24 key: 9fb7a9a5d419da77465797ce1809367c cacheArea: 531 aliveTime: 14400 cacheType: PAGE_CACHE_PAGE_TYPE",
"detailRate": "uri: /detailRate.vm cacheTime: 2013-04-26 22:07:24 key: 9fb7a9a5d419da77465797ce1809367c cacheArea: 531 aliveTime: 14400 cacheType: PAGE_CACHE_PAGE_TYPE"
}
EOD;
var_dump(json_decode($a,1));