0

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)

3 Answers 3

1

With fixed structures you can do that:

$arr = json_decode('{"name": {
    "common": "Italy",
    "official": "Italian Republic",
    "nativeName": {
        "ita": {
            "official": "Repubblica italiana",
            "common": "Italia"
        }
    }
}}',true);

$country = key($arr['name']['nativeName']);  //ita
$common = $arr['name']['nativeName'][$country]['common'];  //Italia

echo '$country = '.$country.', $common = '.$common;

Demo: https://3v4l.org/W4sqI

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.