.JSON文件检索数据-查找值并获取相关对象 [英] .JSON file Retrieving Data - Look for a value and get related objects

查看:683
本文介绍了.JSON文件检索数据-查找值并获取相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    <?php function getCurrencyFor($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            $currency = $country->currency[0];
            $capital = $country->capital;
            $region = $country->region;

            break;
        }
    }
    return $country();
}

$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");

            echo $country('$capital');
            echo $country('$currency');
            echo $country('$region');



?>

我关注了这篇帖子- https://stackoverflow.com/a/38906191/3939981

如果我重写函数中的代码,它会起作用

If I rewrite the code inside function, it works

 <?php function getCurrencyFor($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            $currency = $country->currency[0];
            $capital = $country->capital;
            $region = $country->region;
            echo $capital;
            echo $currency;
            echo $region;
            break;
        }
    }
    return $currency;
}

$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>

也许代码的某些部分无法正常工作.

Maybe some parts of the code did not work..Any comments and thoughs

推荐答案

您可以使用此代码.请注意,如果您希望函数返回三个值,则应使用这些值创建一个数组,然后返回该数组.我还重命名了该函数,因为它不仅返回了货币信息:

You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:

function getCountryInfo($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            return array(
                "currency" => $country->currency[0],
                "capital" => $country->capital,
                "region" => $country->region
            );
        }
    }
}

$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");

echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";

这篇关于.JSON文件检索数据-查找值并获取相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆