Parsing API jSon Array with PHP -



Parsing API jSon Array with PHP -

i stuck next code , not sure why got error code stating have invalid argument in 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 $array) { if ($array[name] == 'jon doe' && $array[id] == '3') { $hours = $array[hours]; } } ?>

html:

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

the api info looks 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 create similar scenario hard coded info , worked fine 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 $array) { if ($array[cname] == 'cc' && $array[pid] == '4') { $occurance = $array[occurances]; } }

html:

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

so little confused doing wrong here api code.

update:

i performed print_r(json_a) after fixing typo (missing comma), , api illustration had "1" result vs. hard coded illustration produced next 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 tried print_r(json_a[0][name]) on api example, , nil returned. have been trying understand have not understood, maybe curl settings? no luck yet. appreciate expert help, new here.

[ {"id":"1","name":"chris smith","hours":"80"}, {"id":"2","name":"tom smith","hours":"70"}, {"id":"3","name":"jon doe","hours":"50"} ]

your api jso wrong formatted.it should have ',' before hours key

php json

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -