我正在使用以下代码解析一些 JSON,但我不断收到意外的 JSON 结果。
它最初来自这里,但我无法让该代码工作,因为第 57 行不是一个数组,所以它抛出了一个与不是数组$status
的事实有关的错误:$status
我通过添加检查来解决这个问题:
56 if (is_array($status)) {}
现在代码运行良好,但返回的 JSON 如下:
{"0":null,"1":" 0"}
我知道这是不正确的,因为当我在 Pebble Watch 上运行应用程序时,它旨在显示正确的数据,但显然失败了,因为0
.
据我所知,应该插入以下代码$order
代替,但由于某种原因null
它总是返回。null
35 // Grab the tube status and the incoming payload.
36 $tube_data = json_decode(file_get_contents($API_URL), true);
37 $payload = get_payload();
38
39 $order = $payload['0'];
40
41 // Start building the response.
42 $response = array(
43 '0' => $order,
44 '1' => ''
45 );
任何帮助将不胜感激,并提前感谢您。
这是完整的代码(包括 utils):
主文件
1 <?php
2
3 // Include my shared functions.
4 include_once($_SERVER['DOCUMENT_ROOT'] . '/utils.php');
5
6 // The URL of the Tube Status API.
7 $API_URL = 'http://api.tubeupdates.com/?method=get.status&format=json';
8
9 // Mapping between shortcode and line name.
10 $line_codes = array(
11 'BL' => 'bakerloo',
12 'CE' => 'central',
13 'CI' => 'circle',
14 'DI' => 'district',
15 'DL' => 'docklands',
16 'HC' => 'hammersmithcity',
17 'JL' => 'jubilee',
18 'ME' => 'metropolitan',
19 'NO' => 'northern',
20 'OV' => 'overground',
21 'PI' => 'piccadilly',
22 'VI' => 'victoria',
23 'WC' => 'waterloocity'
24 );
25
26 // Mapping between errors and numbers
27 $statuses = array(
28 'good service' => 1,
29 'part closure' => 2,
30 'minor delays' => 4,
31 'severe delays' => 8,
32 'part suspended' => 16
33 );
34
35 // Grab the tube status and the incoming payload.
36 $tube_data = json_decode(file_get_contents($API_URL), true);
37 $payload = get_payload();
38
39 $order = $payload['0'];
40
41 // Start building the response.
42 $response = array(
43 '0' => $order,
44 '1' => ''
45 );
46
47 // Split the ordering string into the 2 character line short codes.
48 $lines = str_split($order, 2);
49 foreach ($lines as $pos => $line) {
50
51 // Get the status for the line given its short code.
52 $status = get_status_by_id($line_codes[$line]);
53
54 // Do bitwise ORs on the status number to build it up
55 $status_number = 0;
56 if (is_array($status)) {
57 foreach ($status as $st) {
58 $status_number = $status_number |= $statuses[$st];
59 }
60 }
61
62 // Append the status code to the response string.
63 $response['1'] .= str_pad($status_number, 2, ' ', STR_PAD_LEFT);
64 }
65
66 // Send the response.
67 send_response($response);
68
69 // Takes a line code (not shortcode) and returns an array of its current status.
70 function get_status_by_id($id) {
71 global $tube_data;
72
73 foreach ($tube_data['response']['lines'] as $index => $line) {
74 if ($line['id'] == $id) {
75 return explode(', ', $line['status']);
76 }
77 }
78 return NULL;
79 }
80
81 ?>
实用程序.php
<?php
function get_payload() {
return json_decode(file_get_contents('php://input'), true);
}
function send_response($data) {
$response = json_encode($data, JSON_FORCE_OBJECT);
header('Content-Type: application/json');
header('Content-Length: ' . strlen($response));
echo $response;
exit;
}
?>