Below is my code used to Get data from a REST API to retrieve States .The results contain the State code and State Name to be passed into a select option form with State code as Key and State name as value . My challenge is , i am unable to know the right way to access the data after using json decode
JavaScript
x
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://demo.geminiapp.net/service/Request.svc/api/states",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer yP5lnti7wDChJxwmBYz7dpbgbzGqQRG1dyvAZihesrA=",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
$result = json_decode($response,true);
$result['StateCode']['StateName'];
}
?>
Result of json reponse
{"States":[{"StateCode":"9","StateName":"ABUJA"},{"StateCode":"LA","StateName":"LAGOS STATE"},{"StateCode":"OG","StateName":"OGUN STATE"}]
I have tried to read the response using
$result = json_decode($response,true);
$result['StateCode']['StateName'];
but I get the error
Notice: Undefined index: StateCode
Advertisement
Answer
Based on result
JavaScript
{"States":[{"StateCode":"9","StateName":"ABUJA"},{"StateCode":"LA","StateName":"LAGOS STATE"},{"StateCode":"OG","StateName":"OGUN STATE"}]
After json_decode(), your $result will be this:
JavaScript
[
"States" => [
[
"StateCode" => "9",
"StateName" => "ABUJA",
],
[
"StateCode" => "LA",
"StateName" => "LAGOS STATE",
],
[
"StateCode" => "OG",
"StateName" => "OGUN STATE",
],
]
]
You can simplify it removing the key “States” and holding only its values:
JavaScript
$result = $result["States"];
Now you can iterate $result to see the results, for example:
JavaScript
foreach ($result as $state) {
// do something with your states
echo 'State code: ' . $state['StateCode'] . ' State name: ' . $state['StateName']
}