.JSON file Retrieving Data - Look for a value and get related objects

帅比萌擦擦* 提交于 2019-12-12 03:51:19

问题


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



?>

I followed this post - 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


回答1:


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>";


来源:https://stackoverflow.com/questions/38981696/json-file-retrieving-data-look-for-a-value-and-get-related-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!