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