Monday, 3 September 2018

With Php in a JSON array, how to retrieve the value of an element based on another associated value?

I use json_decode Php function to get a JSON array of countries datas.

{
    "Countries":
    [
        {
            "Code": "AD",
            "Name": "Andorre"
        },
        {
            "Code": "AE",
            "Name": "Émirats Arabes Unis"
        },
        {
            "Code": "AF",
            "Name": "Afghanistan"
        },
        {
            "Code": "AG",
            "Name": "Antigua-Et-Barbuda"
        },

If I want to retrieve the Code of the 1st element I can do:
$result = json_decode($sXML);

$final = $result->Countries[0]->Name;

And $final will have the value of 'Andorre'. But what if I want to retrieve the same value 'Andorre' using its correspoding Code ?
Is it possible to do it ? I know there is an option for the json_function() to obtain an associative array instead of a JSON array, but how would you use it to get the value 'Andorre' using its Code ?
Thank you

Here we are using two function for achieving this array_column and array_combine to retrieve the expected output.
<?php
ini_set('display_errors', 1);
$string='{
    "Countries":
    [
        {
            "Code": "AD",
            "Name": "Andorre"
        },
        {
            "Code": "AE",
            "Name": "Émirats Arabes Unis"
        },
        {
            "Code": "AF",
            "Name": "Afghanistan"
        },
        {
            "Code": "AG",
            "Name": "Antigua-Et-Barbuda"
        }
    ]
    }';
$array=json_decode($string,true);
$codes=  array_column($array["Countries"], "Code");//Retrieving column code
$names=  array_column($array["Countries"], "Name");//Retrieving column name
$data=  array_combine($codes, $names); //combining array with code as keys and names as values.
print_r($data);`

Output:
Array
(
    [AD] => Andorre
    [AE] => Émirats Arabes Unis
    [AF] => Afghanistan
    [AG] => Antigua-Et-Barbuda
)

0 comments:

Post a Comment