使用PHP进行JSON解码
问题描述:
我正在做一些JSON解码-我按照本教程进行了很好的解释-如何使用PHP解析JSON
I am doing some JSON decodes - I followed this tutorial well explained - How To Parse JSON With PHP
和PHP代码,我使用了
and the PHP code, I used
<?php
$string='{"person":[
{
"name":{"first":"John","last":"Adams"},
"age":"40"
},
{
"name":{"first":"Thomas","last":"Jefferson"},
"age":"35"
}
]}';
$json_a=json_decode($string,true);
$json_o=json_decode($string);
// array method
foreach($json_a[person] as $p)
{
echo '
Name: '.$p[name][first].' '.$p[name][last].'
Age: '.$p[age].'
';
}
// object method
foreach($json_o->person as $p)
{
echo '
<br/> Name: '.$p->name->first.' '.$p->name->last.'
Age: '.$p->age.'
';
}
?>
工作正常...但我担心,我只需要Thomas姓氏和年龄的详细信息。我需要处理它以便仅提取某些功能,而不是所有对象。
It is working correctly... But my concern I need only details of Thomas' last name and age. I need to handle this to extract only certain features, not all the objects.
答
给出此JSON ,您可以按以下方式获取国家/地区的货币:
Given this JSON, you can get the currency of a country as follows:
function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
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, "Angola");
echo "Angola has $currency as currency";