I am stuck with the following code and not sure why I got an error code stating I have invalid argument in the foreach() statement.
<?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>
The api data looks like this: (updated)
[
{"id":"1","name":"Chris Smith","hours":"80"},
{"id":"2","name":"Tom Smith","hours":"70"},
{"id":"3","name":"Jon Doe","hours":"50"}
]
I tried to create a similar scenario with hard coded data and it worked just fine like this:
$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.
So I am a little confused what I am doing wrong here with the api code.
Update:
I performed a print_r(json_a) after fixing the typo (missing comma), and the API example had "1" as the result vs. the hard coded example produced the following result:
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 ) )
So I tried print_r(json_a[0][name]) on the API example, and nothing returned. I have been trying to understand what have I not understood, maybe cURL settings? No luck yet. Appreciate expert help, too new here.