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