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":"冯"}]

这样我们就成功地把二维数组转化成了json了.

如有问题,请在下方评论,我会及时回复的.






  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值