php使用json
文章描述:
php如何使用json和操作json
数组转换成Json
json
$json_data= array(
array('id'=>1,'title'=>'地下城与勇士','smalltext'=>'DNF','content'=>'null'),
array('id'=>2,'title'=>'英雄联盟','smalltext'=>'LOL','content'=>'null'),
);
//输出json
echo $json = json_encode($json_data);
结果:
[
{
"id": 1,
"title": "地下城与勇士",
"smalltext": "DNF",
"content": "null"
},
{
"id": 2,
"title": "英雄联盟",
"smalltext": "LOL",
"content": "null"
}
]
乱码转换
echo $json_arr = json_encode($json_data,JSON_UNESCAPED_UNICODE);
//乱码处理
function decodeUnicode($str) {
return preg_replace_callback('/u([0-9a-f]{4})/i',
create_function(
'$matches',
'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
),
$str);
}
Json转换成数组
定义一个json数据格式
$jsons = '{"info":[{"id":1,"title":"\u5730\u4e0b\u57ce\u4e0e\u52c7\u58eb","smalltext":"DNF","content":"null"},{"id":2,"title":"\u82f1\u96c4\u8054\u76df","smalltext":"LOL","content":"null"},{"id":3,"title":"\u7a7f\u8d8a\u706b\u7ebf","smalltext":"CF","content":"null"}]}';
转换数组函数
$str_json = json_decode($jsons,true);
print_r($str_json);
数组开头和结尾添加
$info = array('id'=>3,'title'=>'穿越火线','smalltext'=>'CF','content'=>'null');
//在数组头部添加
array_unshift($items,$info);
//在数组尾部添加
array_push($items,$info);
发布时间:2021/07/06
发表评论