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; ?>
のように、中間プロセスの符号化と復号化により、jsonに変換するプロセスは、自動的に漢字をUnicode文字セットに変えることはない.最後の方法は%BF%AA%D0%C4
の結果は次のとおりです.<?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":" "}]
これで2次元配列をjsonに変換することに成功した.
もし問題があれば、下の方でコメントしてください.すぐに返事します.