Reputation: 97
I am extracting data from a JSON file using a URL like this:
$html5=file_get_contents("url");
$data = json_decode($html5);
echo $data->a->k->f;
This displays $27.58
which is correct.
Here is my JSON data:
{
"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"
}}
I need to display the same data without using k
. For example I want to:
echo $data->a->'Something that specifies first element of 'a' i.e k and not'k_1' and 'k_2'->f;
Since I am scraping this content I cannot change anything like structure or data in this JSON file.
Upvotes: 1
Views: 338
Reputation: 78994
If you just want the first entry under a
, then you can decode as an array:
$data = json_decode($json, true);
Then get the first element of $data['a']
and use that. current()
will also work:
echo reset($data['a'])['f'];
Or re-index $data['a']
numerically and access the first one 0
:
echo array_values($data['a'])[0]['f'];
To catch them all:
foreach($data['a'] as $values) {
echo $values['f'];
//break; if you only want the first one
}
Upvotes: 1
Reputation: 550
You can do this so:
$object = json_decode($html5);
foreach ($object->a as $element) {
echo $element->f;
}
Upvotes: 0