使用JSON数组中的Php如何根据另一个关联值检索项的值?

时间:2017-04-23 14:42:34

标签: php json

我使用json_decode Php函数来获取国家数据的JSON数组。

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

如果我想检索我可以做的第一个元素的代码:

$result = json_decode($sXML);

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

$final将具有'Andorre'的价值。 但是,如果我想使用其对应的代码检索相同的值“Andorre”呢?

有可能吗? 我知道json_function()有一个选项可以获得关联数组而不是JSON数组,但是如何使用它来使用代码获取值“Andorre”?

谢谢

3 个答案:

答案 0 :(得分:2)

<?php

$s = '{
    "Countries":
    [
        {
            "Code": "AD",
            "Name": "Andorre"
        },
        {
            "Code": "AE",
            "Name": "Émirats Arabes Unis"
        },
        {
            "Code": "AF",
            "Name": "Afghanistan"
        },
        {
            "Code": "AG",
            "Name": "Antigua-Et-Barbuda"
        }
    ]
}';

$arr = json_decode($s, true);
print_r(array_column($arr['Countries'], "Name", "Code"));

?>

产量

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

答案 1 :(得分:0)

这里我们使用两个函数来实现此array_columnarray_combine来检索预期的输出。

Try this code snippet here

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

<强>输出:

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

答案 2 :(得分:0)

我想你可以使用类似的东西:

function search_json($obj, $field, $value) {
    foreach($obj as $item) {
        foreach($item as $child) {
            if(isset($child->$field) && $child->$field == $value) {
                return $child->Name;
            }
        }
    }
    return null;
}

print_r(search_json($result, "Code", "AD"));
# Andorre