我有REST API,如下所示:
{
"rajaongkir": {
"query": {
"key": "b5231ee43b8ee75764bd6a289c4c5745"
},
"status": {
"code": 200,
"description": "OK"
},
"results": [
{
"city_id": "1",
"province_id": "21",
"province": "Nanggroe Aceh Darussalam (NAD)",
"type": "Kabupaten",
"city_name": "Aceh Barat",
"postal_code": "23681"
},
{
"city_id": "2",
"province_id": "21",
"province": "Nanggroe Aceh Darussalam (NAD)",
"type": "Kabupaten",
"city_name": "Aceh Barat Daya",
"postal_code": "23764"
}
]
}
}
我想使用此API。我将对象称为以下代码:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Raja Ongkir</title>
</head>
<body>
<h1>Raja Ongkir</h1>
<?php
echo var_dump($data->rajaongkir->results[0]);
?>
</body>
</html>
如果我使用此行调用JSON的第一个元素
echo var_dump($ data-> rajaongkir-> results [0]);
OR
echo var_dump($ data-> rajaongkir-> results [0]-> city_name);
我得到了想要的输出。但是,如果我尝试使用此代码
获取结果对象中的所有 city_id 或 city_nameecho var_dump($ data-> rajaongkir-> results-> city_name);
我收到此错误
消息:试图获取非对象的属性“ city_name”
如何解决?
答案 0 :(得分:1)
请尝试以下操作:
constant
详细信息:
json_decode()
,第二个参数设置为std::integral_constant
,会将JSON转换为[of of arrays]数组。array_column()
函数可用于从二维数组中提取特定键值的一维数组。答案 1 :(得分:1)
您可以对所有城市名称使用循环。 例如:
foreach ($data->rajaongkir->results as $v) {
echo $v->city_name."\n";
}