今天做项目的时候需要用到json数组,解析时遇到了个小小的麻烦,特此将解决办法记下:
json数据如下:
{ "code":200, "message":"ok", "data":[ { "id":78, "title":"模糊", "description":"垃圾", "type":1, "fee":3, "senderPhone":"5534964615", "sender":29, "receiver":null, "sendTime":"2016-03-24 16:59:37", "endTime":"2016-02-24 17:06:00", "longtitude":118.940289, "latitude":32.126177, "finished":0 }, { "id":77, "title":"后门拿货", "description":"一箱水果", "type":1, "fee":1, "senderPhone":"", "sender":29, "receiver":null, "sendTime":"2016-03-24 11:26:15", "endTime":"2016-02-24 11:33:00", "longtitude":118.940289, "latitude":32.126177, "finished":0 }, { "id":76, "title":"", "description":"", "type":1, "fee":1, "senderPhone":"", "sender":29, "receiver":null, "sendTime":"2016-03-24 11:25:02", "endTime":"2016-02-24 11:32:00", "longtitude":118.940289, "latitude":32.126177, "finished":0 }, { "id":75, "title":"", "description":"", "type":1, "fee":1, "senderPhone":"", "sender":29, "receiver":null, "sendTime":"2016-03-24 11:24:58", "endTime":"2016-02-24 11:32:00", "longtitude":118.940289, "latitude":32.126177, "finished":0 }, { "id":74, "title":"jsddhdgg", "description":"纷纷打电话和的", "type":1, "fee":3, "senderPhone":"66485648866", "sender":29, "receiver":null, "sendTime":"2016-03-08 12:34:09", "endTime":"2016-02-08 12:40:00", "longtitude":118.940905, "latitude":32.126506, "finished":0 } ] }
首先讲讲如何获取上面数据中
code 和 message 的方法
其实很简单:
我们将他们赋值给一个变量叫data
$json_string = 'http://52.88.220.193:81/lists.php';//获得json的url $data = curl_file_get_contents($json_string);//通过方法获得json串
想要拿到code的值:
//对data进行编码 $obj = json_decode($data); //获得code 值 $code = $obj->code; $message = $obj->message;
如何拿到data下面的id的值呢?
也很简单:
//data[0] 表示data下第0组 ,下面的意思是第0组的id的值 $arr = $obj->data[0]->id;
其他内容如 title ,type等取法相同
既然取的方法一样 我是不是可以通过循环来做呢?当然可以
不过这里我们知道数据是有5组如果并不知道有几组要如何获取
data有几组数据呢?
用count()方法么?经过测试这个方法似乎并不行,(本人电脑测试,限于环境等因素,不代表所有都不行,可能其他人可以)
我的方法是:先将data的所有数据赋给一个变量,然后使用count()方法计算此数组的大小,事实证明是可行的;:)
$obj = json_decode($data); $size2 = $obj->data; $size2 = count($size2); echo 'data :'.$size2.'<br/>';//显示数组长度