PHP:如何从JSON文件中获取值?
我使用PHP和json_解码来使用远程API,我遇到了一个似乎是新手的问题,我甚至不知道要搜索什么来找到我的答案 因此,在我的脚本中,我有一个$code=392和一个json文件,简化版本为:PHP:如何从JSON文件中获取值?,php,json,Php,Json,我使用PHP和json_解码来使用远程API,我遇到了一个似乎是新手的问题,我甚至不知道要搜索什么来找到我的答案 因此,在我的脚本中,我有一个$code=392和一个json文件,简化版本为: { "result": { "items": [ { "name": "New York", "code": 7294, }, {
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
简单地说,有了代码392,我想知道哪个名字对应于这个代码。怎样?
(实际的json结果有数千个“项”,如果这有区别的话)您可以在json对象的
结果
中迭代项,并检查与所需代码以及每个项的代码是否相等。下面是如何将其实现为函数
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
在上记录首先,您应该解码json数据,如下所示:
foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }
// will decode json data as assoc array
$data = json_decode($json_data, true);
然后,您可以在该数组中获得如下值:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
或
您可以将JSON
转换为PHP对象,并使用foreach
循环遍历项目
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
你可以用这个测试注意:按照rjdown在评论中的建议,删除尾随逗号
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;
您需要编写一个查找代码的foreach
循环。没有内置的方法可以在这样的数组中找到它。只需在示例JSON中添加一个旁注,就不允许像这样留下逗号。PHP的json_解码函数以及一些浏览器将无法解析它。
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;