【发布时间】: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