使用PHP进行JSON解码 [英] JSON DECODE using PHP
本文介绍了使用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";
这篇关于使用PHP进行JSON解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文