我有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->rajangkir->results[0](;
OR
echo var_dump($data->rajangkir->results[0]->city_name(;
我得到了我想要的输出。但是,如果我试图在结果对象中获得所有城市id或城镇名称,请使用以下代码
echo var_dump($data->rajangkir->results->city_name(;
我收到这个错误
消息:正在尝试获取非对象的属性"city_name">
如何修复?
您可以对所有城市名称使用循环。例如:
foreach ($data->rajaongkir->results as $v) {
echo $v->city_name."n";
}
请尝试以下操作:
$all_city_names = array_column(json_decode($data->rajaongkir->results, true),
'city_name');
// Display all the city name(s)
var_dump($all_city_names);
详细信息:
json_decode()
,第二个参数设置为true
,将JSON转换为数组array_column()
函数可用于从二维数组中提取特定键值的一维数组