用PHP解析API jSon数组


Parsing API jSon Array with PHP

我被下面的代码卡住了,不知道为什么我得到一个错误代码,说明我在foreach()语句中有无效的参数。

<?php  
$url = "https://api.example.com";
$headers = array(
    'Content-Type: application/x-www-form-urlencoded', 
    'accesskey: xxxxx', 
    'outputtype: json' 
);
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPGET, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_USERAGENT, $agent);
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($code >= 200 || $code < 300) {
    $json_a = json_decode($response,true);
} else {
    $error = $code;
}
foreach ($json_a as $array) {
    if ($array[name] == 'Jon Doe' && $array[id] == '3') {
        $hours = $array[hours];
    }   
}
?>

HTML:

<div><?php echo $hours; ?></div>

api数据如下:(更新)

[
 {"id":"1","name":"Chris Smith","hours":"80"},
 {"id":"2","name":"Tom Smith","hours":"70"},
 {"id":"3","name":"Jon Doe","hours":"50"}
]

我试图用硬编码的数据创建一个类似的场景,它像这样运行得很好:

$string = '[
        {
            "cID":"7239",
            "cName":"CC",
            "pID":"4",
            "occurances":"2356"
        },
        {
            "cID":"7240",
            "cName":"BB",
            "pID":"5",
            "occurances":"2126"
        },
        {
            "cID":"7250",
            "cName":"AA",
            "pID":"6",
            "occurances":"2456"
        }
]';
$json_a=json_decode($string,true);
foreach ($json_a as $array) {
    if ($array[cName] == 'CC' && $array[pID] == '4') {
        $occurance = $array[occurances];
    }   
}

HTML:

<div><?php echo $occurance; ?></div> //the result shows "2356", which is correct.

所以我有点困惑我在这里用api代码做错了什么。

更新:

在修复打字错误(缺少逗号)后,我执行了print_r(json_a),API示例的结果为"1",而硬编码示例产生了以下结果:

Array ( [0] => Array ( [cID] => 7239 [cName] => CC [pID] => 4 [occurances] => 2356 ) [1] => Array ( [cID] => 7240 [cName] => BB [pID] => 5 [occurances] => 2126 ) [2] => Array ( [cID] => 7250 [cName] => CC [pID] => 6 [occurances] => 2456 ) )

因此,我在API示例中尝试了print_r(json_a[0][name]),但没有返回任何结果。我一直在努力理解我不理解的东西,也许是cURL设置?还没有运气。感谢专家的帮助,这里太新了。

[
 {"id":"1","name":"Chris Smith","hours":"80"},
 {"id":"2","name":"Tom Smith","hours":"70"},
 {"id":"3","name":"Jon Doe","hours":"50"}
]

你的api jso格式错误。它应该在小时前有","键

我做到了!以下是我的想法,结果是我应该将CURLOPT_RETURNTTRANSFER设置为true,代码就工作了。

无论如何,感谢大家的帮助。