浅谈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":"u67e5u8be2u6210u529f","content":[{"client_id":"000003","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"},{"client_id":"000002","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"},{"client_id":"000001","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"},{"client_id":"000000","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"},{"client_id":"000004","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"},{"client_id":"000005","client_name":"u5f90u5229u5175","client_phone":"18813752547","client_address":"u5e7fu4e1cu97f6u5173u7fc1u6e90","client_picture":"http://www.baidu.com","user_id":"18813752547"}]}
 
2、不存在用户的:
 
{"status":"error","msg":"u67e5u8be2u9519u8bef","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
原文地址:https://www.cnblogs.com/xulibing/p/5276972.html