PHP:如何从JSON文件获取值?

博克齐尔

我正在使用PHP和json_decode使用远程API,并且遇到了似乎是新手问题,但我什至不知道要搜索什么才能找到答案。

所以在我的脚本上,我有一个$ code = 392和一个json文件,其简化版本是:

{
    "result": {
        "items": [
            {
                "name": "New York",
                "code": 7294,
            },
            {
                "name": "Miami",
                "code": 392,
            },
            {
                "name": "Los Angeles",
                "code": 9182,
            }
        ]
    }
}

因此,简而言之,拥有代码392,我想知道哪个名称与该代码相对应。如何 ?(实际的json结果有成千上万个“项目”,如果有区别的话)

奥斯汀·布伦霍斯特(Austin Brunkhorst)

您可以遍历JSON对象的itemsin result,并检查与所需代码以及每个项目的代码是否相等。这是将其实现为函数的方式。

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);

关于的文档foreach()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章