浅谈thinkphp中将字符串转换成json数组的方法
Posted 飞侠之殇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅谈thinkphp中将字符串转换成json数组的方法相关的知识,希望对你有一定的参考价值。
这是一部分代码:
$client = M("Client");
$data = $client->where(\'user_id =\'.$user_id)->select();
if($data == false || $data == null)
{
/*查询错误*/
$str = array(
\'status\' => \'error\',
\'msg\' => \'查询错误\',
\'content\'=> \'null\'
);
$this->ajaxReturn($str);
}
else
{
/*查询成功*/
$str = array(
\'status\' => \'success\',
\'msg\' => \'查询成功\',
\'content\'=> $data
);
$this->ajaxReturn($str);
}
注意一下:php比较两个字符串尽量不要用 == 来比较,会出现意料不到的后果;尽量用strcmp来比较,当结果为0 的时候表示想等。
这是两种结果:
1、存在用户的:
{"status":"success","msg":"\\u67e5\\u8be2\\u6210\\u529f","content":[{"client_id":"000003","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"},{"client_id":"000002","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"},{"client_id":"000001","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"},{"client_id":"000000","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"},{"client_id":"000004","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"},{"client_id":"000005","client_name":"\\u5f90\\u5229\\u5175","client_phone":"18813752547","client_address":"\\u5e7f\\u4e1c\\u97f6\\u5173\\u7fc1\\u6e90","client_picture":"http:\\/\\/www.baidu.com","user_id":"18813752547"}]}
2、不存在用户的:
{"status":"error","msg":"\\u67e5\\u8be2\\u9519\\u8bef","content":"null"}
相信大家都很关心一个问题:就是在android客户端如何解析这种json格式?我来为大家解答一下:
假设实现了android客户端将从服务器读取过来的内容保存在buider里面,则接下来:
JSONObject jsonobject1 = new JSONObject(builder.tostring()).getJSONObject(“status”);
JSONObject jsonobject2 = new JSONObject(builder.tostring()).getJSONObject(“msg”);
JSONObject jsonobject3 = new JSONObject(builder.tostring()).getJSONObject(“content”);
String client_id = jsonobject3.getString(“client_id”);
String client_name = jsonobject3.getString(“client_name”);
…………
一次类推。
至于其他格式的json解析,自行网上查找方法。
可以参考一下这个:http://www.cnblogs.com/cpcpc/archive/2011/07/22/2122989.html
以上是关于浅谈thinkphp中将字符串转换成json数组的方法的主要内容,如果未能解决你的问题,请参考以下文章