how to get API data from nested array by php - 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.

Related

How to put foreach in array

I have this
$homedata = $user->getbanks();
foreach ($homedata as $data)
echo json_encode(array("replies" => array(array("message" => $data->bankname))));
I have this put the result am getting is only one array from the list. I want to get all.
If I understand your requirement correctly, you need the banknames in an array replies within a key message. For that the below code will do the job. But you can optimize the query for better performance.
$homedata = $user->getbanks();
$banks['replies'] = [];
foreach ($homedata as $data) {
$banks['replies'][]['message'] = $data->bankname;
}
print_r(json_encode($banks)); exit;
Further, you were only getting the first content because you are overriding the previous content when you iterate using foreach.

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

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>";
}

How to get properties through loop from a REST JSON response using Httpfull in PHP and how to show in grid

As in the URL, I don't want to give a limit, I want to show in loop
[0]. I don't want to give [0] or [1] etc. I want to do it in a loop.
http://buildout.com/api/v1/d7d8b6a8cbd23c1f69e3a327b32c8217d6bea635/properties.json?limit=2
<?php
$url='my url';
$res = \Httpful\Request::get($url)->expectsJson()->send();
$data = json_decode($res,true);
$name1 = $data['properties'][0]['broker_id']; // I WANT LOOP HERE INSTED OF [0]
echo $city1;
?>
You can loop through the response data dynamically to get each datum without specifying the index as follows:
foreach ($data['properties'] as $key=>$val) {
var_dump($key);
}
The $key can be:
First $data['properties'][0];
Next $data['properties'][1];
and so on...

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'];
}
}

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