繁体   English   中英

如何使用 php 从多维 json 响应中获取键和值

[英]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. 我的挑战是,在使用 json 解码后,我无法知道访问数据的正确方法

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

根据结果

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

在 json_decode() 之后,你的 $result 将是这样的:

[
   "States" => [
        [
            "StateCode" => "9",
            "StateName" => "ABUJA",
        ],
        [
            "StateCode" => "LA",
            "StateName" => "LAGOS STATE",
        ],
        [
            "StateCode" => "OG",
            "StateName" => "OGUN STATE",
        ],
    ]
]

您可以将其简化为删除键“States”并仅保留其值:

$result = $result["States"];

现在您可以迭代 $result 以查看结果,例如:

foreach ($result as $state) {
    // do something with your states
    echo 'State code: ' . $state['StateCode'] . ' State name: ' . $state['StateName']
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM