Access Element in JSON data that doesn't have a standard name - php

I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!

Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}

Related

how to get API data from nested array by php

I want to get the data from array inside array as per the below code :
{"address":"0x64890972513558cb4e4b4a7f8af48d892fd097b7","ETH":{"**balance**":0,"totalIn":0,"totalOut":0},"countTxs":0,"tokens":[{"**tokenInfo**":{"**address**":"0xad640689e6950b7453729a4686edb3fdfd754616","**name**":"CIChain","decimals":"18","symbol":"CIC","totalSupply":"3000000000000000000000000000","owner":"0xecb64b92ffb5179b47c87d2f105d6eeebb132c68","lastUpdated":1527246490,"issuancesCount":0,"holdersCount":31528,"**price**":false}
i'm using this steps but I couldn't continue :
$address = "0x64890972513558cb4e4b4a7f8af48d892fd097b7"; //$_POST['address'];
$scan_url = 'https://api.ethplorer.io/getAddressInfo/'.$address.'?apiKey=freekey';
$scan_json = file_get_contents($scan_url);
$scan_array = json_decode($scan_json, true);
foreach($scan_array['tokens'] as $key => $eth) {
foreach($eth['tokenInfo'] as $key => $etth) {
echo $etth['name'];
}}
I want to retrieve the marked date by stars ** into echo in php so how can I get the nested data.
According to your url given you need to change you code like below
$scan_array = json_decode($scan_json, true);
foreach($scan_array['tokens'] as $key => $eth) {
echo $eth['tokenInfo']["name"]. "\n";
}
Live demo
Second foreach is giving all element from tokenInfo so either no need to use inner foreach or to get all element no need to use like $etth['name'] this, only $etth will give is enough.

Loop through nested arrays PHP

Im trying to loop through PHP arrays decoded from a json file. I get the results but it only gives me the first results of the arrays in the the file. How can I make it loop? This is my code:
foreach ($events as $event) {
echo $event['d']['Tree1'][0]['Tree2']['Field1'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field2'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field3'] . '<br>';
}
Sounds like you're trying to loop through the values of a "multidimensional array". You're starting correctly by going through your array with a loop, but then you're stuck because each element in your loop is... another array. So, to echo out the values of the child array, you want to run a second loop inside of your loop. Essentially, if your loop hits a child array, you want to loop through that array too. If you know your array is made of child arrays only, you can do this like so:
<?php
foreach ($events as $event) {
foreach($event as $ev) {
echo $ev;
}
}
If you need the keys, that adds a slight layer of complexity, but nothing you can't manage.
<?php
foreach ($events as $event) {
foreach ($event as $k=>$v) {
echo $k .': '. $v;
}
}
There are some examples in the php manual as well. You can also add in conditionals if you only need data from specific keys. Good luck!

Parsing JSON in for each with increment PHP

I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}

Pull data from nested json loop php

Ok, I have been fighting this for two days now!! Here is my Json structure.
[
{
"uuid":"/random number==",
"meeting_number":7196503037,
"host_id":"random number",
"topic":"My's Personal Meeting Room",
"start_time":"2015-01-06T22:01:07Z",
"timezone":"America/Denver",
"duration":56,
"total_size":378080,
"recording_count":1,
"recording_files":[
{
"id":"long number",
"meeting_id":"/NS90bsSTLeGzo6cT0nwXw==",
"recording_start":"2015-01-06T22:01:09Z",
"recording_end":"2015-01-06T22:01:14Z",
"file_size":378080,
"play_url":"https://myurl"
}
]
},
I am trying to pull the Start Time from the top level array (which is named 'meetings') and the Play Url from the second level array (recording_files). I am using json_decode to decode the file into arrays.
I have tried many variations found on this site and nothing seems to get to the play url.
VARIATION 1
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
foreach($key['recording_files'] as $subkey => $newvalue){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}}
This pulls an invalid argument in foreach.
VARIATION 2
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This pulls undefined index for play_url. As does the same code with the reference to ['recording_files'] placed before ['play_url']
VARIATION 3:
Then I tried giving up on the first level and just pulling data from the second level:
$aha = json_decode($response,true);
foreach ($aha['meetings']['recording_files'] as $key => $value){
echo '<p>Time : '.$value['recording_start'].'</p>
Recording<br>';
}
That gives me an undefined index on ['recording_files'] and a foreach error.
VARIATION 4.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
$link=$key['recording_files'];
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This gets me the closest - no errors but no link. I presume that here the code is seeing the field but just not pulling the data from it...
Please help a newbie json person!!
If there is really an $aha['meetings'] (you don't show it), then use the value not the key in the second foreach:
foreach($aha['meetings'] as $value){
foreach($value['recording_files'] as $newvalue){
Final code that fixed it.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';}
It was just a matter of finding the correct format for referencing the play_url piece.
Thank you so much to everyone!
Edit:
If your data looks like this :
$str = "{\"meetings\":[{
\"uuid\":\"/random number==\",
\"meeting_number\":7196503037,
\"host_id\":\"random number\",
\"topic\":\"My's Personal Meeting Room\",
\"start_time\":\"2015-01-06T22:01:07Z\",
\"timezone\":\"America/Denver\",
\"duration\":56,
\"total_size\":378080,
\"recording_count\":1,
\"recording_files\":[
{
\"id\":\"long number\",
\"meeting_id\":\"/NS90bsSTLeGzo6cT0nwXw==\",
\"recording_start\":\"2015-01-06T22:01:09Z\",
\"recording_end\":\"2015-01-06T22:01:14Z\",
\"file_size\":378080,
\"play_url\":\"https://myurl\"
}
]
}]}";
$json = json_decode($str);
$res = $json->{'meetings'};
foreach($res as $keys){
echo $keys->{'start_time'}."<br>";
foreach ($keys->{'recording_files'} as $data){
echo $data->{'play_url'}."<br>";
echo $data->{'recording_start'}."<br>";
}
}

PHP - using foreach with array

I'm struggling to get the correct syntax to to parse out the values from an array to use with the foreach loop. I have an array:
$contacts_array
which contains one or more names which I need to search on. The array looks like this:
Array
(
[0] => PR1010
[1] => PR1086
)
If I was to manually generate the required PHP code with a known number of names it would look like this where there are 2 names to search on:
// Create first find request
$findreq1 =$fm->newFindRequest('Contacts');
// Create second find request
$findreq2 =$fm->newFindRequest('Contacts');
// Specify search criterion for first find request
$findreq1->addFindCriterion('Name', $searchTerm);
// Specify search criterion for second find request
$findreq2->addFindCriterion('Suburb', $searchTerm);;
// Add find requests to compound find command
$request->add(1,$findreq1);
$request->add(2,$findreq2);
I need to generate the equivalent code for every name in the array. I know I need to use something like:
foreach($contacts_array as $contact_array => $value)
{
}
as well as:
$num = 1
$num++; } /* foreach record */
I'm just not sure how to bring this all together so that it increments the $findreq1 variables as I go. All my attempts so far generate errors. If anyone can show me how to combine this together that would be greatly appreciated as I'm learning PHP as I go.
Thanks
<?php
for($i = 0; $i < count($contacts_array); $i++) {
${'findreq' . ($i+1)} = $fm->newFindRequest('Contacts');
${'findreq' . ($i+1)}->addFindCriterion('Name', $contacts_array[$i]);
$request->add($i+1, ${'findreq' . ($i+1)});
}
?>
Read more about Dynamic variable names in PHP
You guys beat me to it.
<?php
$contacts = Array('PR1010','PR1086');
//print_r($contacts);
foreach ($contacts as $key => $value) {
//echo "key: ".$key." - Value: ".$value."<br>";
$findreq1 = $fm->newFindRequest('Contacts');
$findreq1->addFindCriterion('Name', $value); // this is where the Array's value is passed too, it is looped for every value in the Array
$request->add(1,$findreq1);
// do more here
}
?>

Categories