PHP JSON 操作,phpjson操作
由于JSON可以在很多种程序语言中使用,所以我们可以用来做小型数据中转,如:PHP输出JSON字符串供JavaScript使用等。在PHP中可以使用 json_decode() 由一串规范的字符串解析出 JSON对象,使用 json_encode() 由JSON 对象生成一串规范的字符串。
例:
$json = '{"a":1, "b":2, "c":3, "d":4, "e":5 }';
var_dump(json_decode($json));
var_dump(json_decode($json,true));
输出:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
输出:{"a":1,"b":2,"c":3,"d":4,"e":5}
1. json_decode(),字符转JSON,一般用在接收到Javascript 发送的数据时会用到。
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo '网站名称:'.$web->webname.'
网址:'.$web->url.'
联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;
?>
上面的例子中,我们首先定义了一个变量s,然后用json_decode()解析成JSON对象,之后可以按照JSON的方式去使用,从使用情况看,JSON和XML以及数组实现的功能类似,都可以存储一些相互之间存在关系的数据,但是个人觉得JSON更容易使用,且可以使用JSON和JavaScript实现数据共享。
2. json_encode(),JSON转字符,这个一般在AJAX 应用中,为了将JSON对象转化成字符串并输出给 Javascript 时会用到,而向数据库中存储时也会用到。
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo json_encode($web);
?>
二 .PHP JSON 转数组
$s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';
$web=json_decode($s); //将字符转成JSON
$arr=array();
foreach($web as $k=>$w) $arr[$k]=$w;
print_r($arr);
?>
上面的代码中,已经将一个JSON对象转成了一个数组,可是如果是嵌套的JSON,上面的代码显然无能为力了,那么我们写一个函数解决嵌套JSON,
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
$arr=json_to_array($web);
print_r($arr);
function json_to_array($web){
$arr=array();
foreach($web as $k=>$w){
if(is_object($w)) $arr[$k]=json_to_array($w); //判断类型是不是object
else $arr[$k]=$w;
}
return $arr;
}
?>

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1
強大的PHP整合開發環境