【问题标题】:how can I get the key and value from a multidimensional json response using php如何使用 php 从多维 json 响应中获取键和值
【发布时间】:2021-03-15 22:16:39
【问题描述】:

以下是我用于从 REST API 获取数据以检索状态的代码。结果包含状态代码和状态名称,将被传递到选择选项表单中,状态代码作为键,状态名称作为值。 我的挑战是,我无法知道使用 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
   

【问题讨论】:

  • 除非您向我们展示该数组的内容是什么,否则我们无法提供帮助。

标签: php json curl multidimensional-array


【解决方案1】:

根据结果

{"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']
}

【讨论】:

  • 完美答案。
猜你喜欢
  • 2022-07-18
  • 2017-08-24
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多