php解析多层json
A. php如何解析json
用json_decode函数将json字符串转换为数组
<?php
$json = '{"multi-i1ndex-style":{"old":{"0.1":"123","0.2":"234"}}}';
echo "<pre>";
print_r(json_decode($json, true));
echo "</pre>";
B. 如何使用PHP接收JSON数据
在PHP中接收JSON数据,关键在于使用`php://input`和`file_get_contents()`函数。`php://input`是一个只读流,可读取请求正文中的原始数据,而`file_get_contents()`用于将文件读入字符串,这为我们提供了处理JSON数据的途径。
一旦获取到请求正文,我们使用`file_get_contents('php://input')`将数据读入一个字符串。然后,使用`json_decode()`函数解析这个字符串。`json_decode()`接受一个JSON格式的字符串,将其转换为PHP变量,该变量可以是数组或对象,从而实现对JSON数据的接收和处理。
使用`$_POST`全局变量接收数据时,如需处理JSON格式的数据,通过上述方法更为高效。首先,使用`file_get_contents('php://input')`读取请求正文数据。接着,使用`json_decode()`函数将JSON数据解码为PHP变量。这样一来,你便能顺利地在PHP脚本中接收和操作JSON数据了。
C. android怎么解析PHP返回的多维JSON数组格式
首先贴一段示例代码:
<?php
include "con_db.php";//连接数据库
$sql="select * from note order by note_date desc limit ".($index*10).",10"; //sql语句
$result=mysql_query($sql);//获得结果
$note;$i=0; //初始化变量
while($infor=mysql_fetch_array($result))
{
//把结果放到一个一维数组里
$note["id"]=$infor['note_id'];
$note["content"]=$infor['note_content'];
$note["date"]=$infor['note_date'];
$note["username"]=$infor['username'];
//放到二维数组里
$notes[$i++]=$note;
}
echo json_encode($notes );
?>
输出结果:
[{"id":"12","content":"u662f","date":"2014-05-24 09:31:52","username":"u532f"},
{"id":"31","content":"u642f","date":"2014-05-24 09:31:49","username":"u322f"},
{"id":"70","content":"u692f","date":"2014-05-24 09:31:48","username":"u132f"}]
你会发现应该输出的汉字变成了unicode字符集.
这时我们就要用到urlencode的方法,把汉字用urlencode方法编码,转化为json之后再用urldecode解码.看如下例子:
<?php
$h =urlencode("开心");
echo $h;
$x =urldecode($h);
echo $x;
?>
输出结果:
%BF%AA%D0%C4开心
这样通过中间过程的编码和解码,转化成json的过程便不会自动把汉字变成Unicode字符集了.所以最后的方法为:
<?php
while($infor=mysql_fetch_array($re))
{
$note["id"]=$infor['note_id'];//数字不需要编码
$note["content"]=urlencode($infor['note_content']);//汉字需要编码
$note["date"]=$infor['note_date'];
$note["username"]=urlencode($infor['username']);
$notes[$i++]=$note;
}
echo urldecode(json_encode($notes ));//转化成json之后再用urldecode解码为汉字
?>
结果如下:
[{"id":"22","content":"文章","date":"2014-05-24 09:31:52","username":"王"},
{"id":"21","content":"内容","date":"2014-05-24 09:31:49","username":"李"},
{"id":"20","content":"可以","date":"2014-05-24 09:31:48","username":"冯"}]
参考资料:http://cuiqingcai.com/?p=27