Skip to content
Advertisement

how can I get the key and value from a multidimensional json response using php

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

<?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

{"States":[{"StateCode":"9","StateName":"ABUJA"},{"StateCode":"LA","StateName":"LAGOS STATE"},{"StateCode":"OG","StateName":"OGUN STATE"}]

After json_decode(), your $result will be this:

[
   "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:

$result = $result["States"];

Now you can iterate $result to see the results, for example:

foreach ($result as $state) {
    // do something with your states
    echo 'State code: ' . $state['StateCode'] . ' State name: ' . $state['StateName']
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement