比较 php 中的 JSON 个字符串

Compare JSON strings in php

我有一个这样的国家 json 文件

[
    {
        "name": "Afghanistan",
        "code": "AF"
    },
    {
        "name": "Åland Islands",
        "code": "AX"
    },
    {
        "name": "Albania",
        "code": "AL"
    },
    {
        "name": "Algeria",
        "code": "DZ"
    },
    {
        "name": "American Samoa",
        "code": "AS"



<?php
    $string = file_get_contents('countries.json');
    $array = json_decode($string, true);

    foreach ($array as $person_name => $person_a) {
        if(strcmp($person_name,'HR')==0)
        {
            echo $person_a['name'].'<br>';
        }
}
?>

我需要将 'code' 与给定值进行比较,然后输出匹配的国家/地区,我如何找到 ex 的代码。 'GB' 然后输出 'Great Britain'?

使用array_search with array_column1:

$found = array_search( 'DZ', array_column( $array, 'code' ) );
if( $found === False ) echo "Not Found";
else                   echo $data[$found]['name'];

array_column returns 所有 'code' 值:使用 array_search 检索相应的键,如果找到,则可以回显相应的名称。


1 可用 PHP >= 5.5