我使用这样的URL从JSON文件中提取数据:
$html5=file_get_contents("url");
$data = json_decode($html5);
echo $data->a->k->f;
这会显示$27.58
这是正确的。
这是我的JSON数据:
{
"a":{
"k":{
"c":"tr",
"f":"$27.58",
"fb":"$30.35",
"ci":"12873809",
"cname":"Cdkeysgame_com",
"ep":"26.05",
"epb":"28.66",
"a":"5473091",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"retail",
"ne":0,
"so":0,
"tr":304,
"r":97,
"cf":1,
"p":"27.58317275",
"pb":"30.3467843",
"eci":"865723abbf1cbb952ad4d2da8a8c925e"
},
"k_1":{
"c":"gb",
"f":"$27.64",
"fb":"$30.40",
"ci":"1065801",
"cname":"World_of_games",
"ep":"26.10",
"epb":"28.71",
"a":"781851",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"all",
"ne":0,
"so":0,
"tr":1041328,
"r":99,
"cf":1,
"p":"27.6361155",
"pb":"30.39972705",
"eci":"d01a7cacb0e424123985bfe2e53a0523"
},
"k_2":{
"c":"ch",
"f":"$27.68",
"fb":"$30.44",
"ci":"696012",
"cname":"G_hard",
"ep":"26.14",
"epb":"28.75",
"a":"1287052",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"retail",
"ne":0,
"so":0,
"tr":10818,
"r":99,
"cf":1,
"p":"27.6784697",
"pb":"30.44208125",
"eci":"a6666c0a47acb70d14b757cd52f1b9cc"
}}
我需要在不使用k
的情况下显示相同的数据。例如,我想:
echo $data->a->'Something that specifies first element of 'a' i.e k and not'k_1' and 'k_2'->f;
由于我正在抓取此内容,因此无法更改此JSON文件中的结构或数据。
答案 0 :(得分:1)
如果您只想要a
下的第一个条目,那么您可以解码为数组:
$data = json_decode($json, true);
然后获取$data['a']
的第一个元素并使用它。 current()
也可以运作:
echo reset($data['a'])['f'];
或者以数字方式重新索引$data['a']
并访问第一个0
:
echo array_values($data['a'])[0]['f'];
抓住他们所有人:
foreach($data['a'] as $values) {
echo $values['f'];
//break; if you only want the first one
}
答案 1 :(得分:0)
你可以这样做:
$object = json_decode($html5);
foreach ($object->a as $element) {
echo $element->f;
}