本文实例分析了PHP针对JSON操作。分享给大家供大家参考。具体分析如下:
由于JSON可以在很多种程序语言中使用,所以我们可以用来做小型数据中转,如:PHP输出JSON字符串供JavaScript使用等。在PHP中可以使用 json_decode() 由一串规范的字符串解析出 JSON对象,使用 json_encode() 由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 发送的数据时会用到。
复制代码 代码如下:<"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo '网站名称:'.$web->webname.'<br />网址:'.$web->url.'<br />联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;
"codetitle">复制代码 代码如下:<"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo json_encode($web);
"codetitle">复制代码 代码如下:<"webname":"homehf","url":"www.homehf.com","qq":"123456789"}';
$web=json_decode($s); //将字符转成JSON
$arr=array();
foreach($web as $k=>$w) $arr[$k]=$w;
print_r($arr);
"codetitle">复制代码 代码如下:<"webname":"homehf","url":"www.homehf.com","contact":{"qq":"123456789","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;
}
?>
希望本文所述对大家的php程序设计有所帮助。
PHP,JSON,操作
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]
- 周冰倩1995《沧桑情歌》JVC日本录制[WAV+CUE]
- 辛禄乐队.2024-热烈的少年【星辰】【FLAC分轨】
- 成龙.1996-龙的心【滚石】【WAV+CUE】
- 童安格.1991-一世情缘【宝丽金】【WAV+CUE】
- 韩红2010-擦肩而过[央金玛][WAV+CUE]
- RiccardoTesi-UnballoLiscio,Vol.II(2024)[24-48]FLAC
- 金池VS刘罡2009《双声情》[WAV+CUE]
- 冯奥迪《卄》[320K/MP3][67.08MB]
- 冯奥迪《卄》[FLAC/分轨][172.46MB]