I have this part of a JSON file:
And the next record:
I need to get several fields from each record. For instance [City].
With this code I can get the first city:
$response = curl_exec($ch);
$result = json_decode($response, true);
echo $result['GetLocationsResult']['ResponseLocation'][0]['Address']['City'];
However I want to loop through all the records and get all [City] fields.
This should be quite straight forward
$locations = $result['GetLocationsResult']['ResponseLocation'];
$cities = [];
foreach($locations as $location)
{
$cities[] = $location['Address']['City'];
}
var_dump($cities);
This is a more modern approach to getting all the cities, we don't need any loop anymore:
$cities = array_map(
fn($location) => $location['Address']['City'],
$result['GetLocationsResult']['ResponseLocation']
);
print_r($cities);
It depends on what exactly you need from the array whether this suits.
The true param of the json_decode tells you that the decoded json is an associative array. Thus you can use it as an array an loop over the values you want as you would threat any other array.
Related
I'm new to PHP and web programming at all.I am trying to read some json data from steam API.
Data: http://pastebin.com/hVWyLrfZ
I managed to get to single objects(I believe?).
This is my code:
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
I want data to be in array like this:
id => name
I mean, array keys should be ids and values should be hero names.
Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?
You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(No need to do any reset calls; that's a weird way to get the first element of an array)
Note, for this to work, you must apply the tip by #RamRaider
$data = json_decode($JSON, true);
in order for json_decode to return arrays, not StdClass.
I have the following JSON array:
{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}
Using PHP is it possible to display a specific recurring value, for example if I wanted to display "key1" in a foreach loop it would return the following:
Example1
Example5
Example9
Appreciate any tips on what to use to do this, thanks.
You aren't going to be able to do this using json_encode because it's not valid JSON. (Keyspace collision)
You are going to need to assemble the object manually.
You might consider creating the individual items, then using implode(). Then you can prepend and append { and }.
<?php
$jsonObject='{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}';
$jsonArray = array_map(
function($array){
$keyValue=explode(":",$array);
return array("key"=>substr($keyValue[0],1,-1),"value"=>substr($keyValue[1],1,-1));
},
explode(
",",
substr($jsonObject,1,-1)
)
);
foreach($jsonArray as $object){
$output[$object['key']][]=$object['value'];
}
echo implode("\n",$output['key1']);
?>
Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;
I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];
This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);