Home > Enterprise >  PHP - Get the value of an unknown array key
PHP - Get the value of an unknown array key

Time:11-09

Based on this result from an API

"name": {
    "common": "Italy",
    "official": "Italian Republic",
    "nativeName": {
        "ita": {
            "official": "Repubblica italiana",
            "common": "Italia"
        }
    }
},

Let's suppose i always want the "common" name but, depending on the country the "key" will vary (now it's "ita" but it could be anything)

What is the cleanest way to always get the "common" value independently of the key name above? (so a dynamic function that always get the common value)

CodePudding user response:

You could iterate over that part of the data structure like this to get both the key and the value of common

$json = '{
    "name": {
    "common": "Italy",
    "official": "Italian Republic",
    "nativeName": {
        "ita": {
            "official": "Repubblica italiana",
            "common": "Italia"
        }
    }
}
}';


foreach (json_decode($json)->name->nativeName as $key => $native){
    echo "Key = $key, common = {$native->common}";
}

RESULT

Key = ita, common = Italia

CodePudding user response:

You can use get_mangled_object_vars() with key() if you have just one nativeName like:

$a = json_decode('{"name": {
    "common": "Italy",
    "official": "Italian Republic",
    "nativeName": {
        "ita": {
            "official": "Repubblica italiana",
            "common": "Italia"
        }
    }
}}');
print_r(key(get_mangled_object_vars($a->name->nativeName))); // ita

Reference:


Or you can use ArrayObject combine with getIterator() and key() like:

$a = json_decode('{"name": {
        "common": "Italy",
        "official": "Italian Republic",
        "nativeName": {
            "ita": {
                "official": "Repubblica italiana",
                "common": "Italia"
            }
        }
}}');
$arrayobject = new ArrayObject($a->name->nativeName);
$iterator = $arrayobject->getIterator();
echo $iterator->key(); //ita

Reference:

  • Related