I want to decode json code with php in wordpress.
this is my code. but did not work.
function decode_func(){
$json = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
$decoded_json = json_decode($json,true);
$results = $decoded_json['results'];
foreach($results as $result) {
$datetime = $result['datetime'];
foreach($datetime as $datetim) {
$times = $datetim['times'];
foreach($times as $time) {
echo $time['Sunrise'];
}
}
}
}
add_shortcode('decode','decode_func');
I tested your code and what I found out is that your property targeting is incorrect.
In order to get the Sunrise property by foreach loops alone and not directly targeting that property you need to do the following.
$json = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
$decoded_json = json_decode($json,true);
$results = $decoded_json['results'];
foreach ($results as $key => $result) {
if ($key !== 'datetime') continue;
foreach($result as $datetime) {
foreach ($datetime as $time) {
if (!empty($time['Sunrise'])) echo $time['Sunrise'];
}
}
}
EDIT
In order to get the city as well I created a new if condition with a elseif.
The code is almost the same, because location is not a multi dimentional array its less foreachs to get the city value
$json = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
$decoded_json = json_decode($json,true);
$results = $decoded_json['results'];
foreach ($results as $key => $result) {
if ($key === 'datetime') {
foreach($result as $datetime) {
foreach ($datetime as $time) {
if (!empty($time['Sunrise'])) echo $time['Sunrise'];
}
}
} else if ($key === 'location') {
if (!empty($result['city'])) echo $result['city'];
}
}
Related
The goal here is to have the Name Printed followed by the values
IE Tromsø: 33,28 30,00
Im very novice at this and have been struggling with this one for a few days trying to lookup nested PHP examples and just gives me an error
<?php
$people_json = file_get_contents('https://www.nordpoolgroup.com/api/marketdata/page/10?currency=,,,EUR');
$decoded_json = json_decode($people_json, true);
$data = $decoded_json['data'];
$filter = "Tromsø";
foreach($row as $Rows) {
echo( $filter.": " );
foreach($Columns as $row['Columns']) {
if($filter==$Columns['Name'])
{
echo($Columns['Value']. " ");
}
}
}
?>```
Your foreach statements are the wrong way around; it should be
foreach ($array as $value)
where you have
foreach ($value as $array)
Once you correct that, your code works fine (with some minor cleanup):
$decoded_json = json_decode($people_json, true);
$data = $decoded_json['data'];
$filter = "Tromsø";
echo( $filter.": " );
foreach ($data['Rows'] as $row) {
foreach ($row['Columns'] as $column) {
if ($filter==$column['Name']) {
echo $column['Value']. " ";
}
}
}
Output (for the first two rows of the data):
Tromsø: 33,28 30,00
Demo on 3v4l.org
I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13
I am probably searching wrong but I havent been able to find a topic that fully helps understand how to pull all the data out of this multidimensional array from a json file. I am trying to pull all data that is related to a certain term or piece of data and return its key and value.
So far I have tried this and its somewhat works.
JSON - https://gist.github.com/Ryahn/ac8fcc8ae77e9a6ee9138e268b592ed3
$result = file_get_contents('21st.json');
$json = json_decode($result,true);
$term = 871957;
foreach ($json as $key => $value)
{
if ($value = $term)
{
echo $value;
echo $key;
foreach ( $value as $key1 => $value2 )
{
if ($value2 = $term)
{
echo $value2;
echo $key1;
foreach ( $value2 as $key2 => $value3 )
{
echo $value3;
}
}
}
}
}
There are multiple levels and parents that may be tied to one ID. I have yet to figure out how to pull all them at once.
Thank you in advance <3
Try this, using isset to check if the user is in the users section and array_filter plus in_array to search the tag users array:
$result = file_get_contents('21st.json');
$json = json_decode($result,true);
$userId = 871957;
$user = isset($json['users'][$userId]) ? $json['users'][$userId] : null;
$tags = [];
if ($user) {
$tags = array_filter($json['tags'], function($tag) use ($userId) {
return in_array($userId, $tag['users']);
});
}
$tagIds = array_keys($tags);
Some tweaking in your code, Replaced = to ==
$result = file_get_contents('21st.json');
$json = json_decode($result,true);
$term = 871957;
foreach ($json as $key => $value)
{
if ($value == $term)
{
echo $value;
echo $key;
foreach ( $value as $key1 => $value2 )
{
if ($value2 == $term)
{
echo $value2;
echo $key1;
foreach ( $value2 as $key2 => $value3 )
{
echo $value3;
}
}
}
}
}
P.S First check this if it is ok so kindly tell me.
<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places
I am currently getting the output I desire, although It seems that the only way I can get this to work is with these nasty nested foreach loops. I know that there must be a better way to loop this this JSON object.
$json = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$fbObject = file_get_contents($json);
$array = json_decode($fbObject, true);
$count = 0;
if(is_array($array))
{
foreach ($array as $key => $object) {
if(is_array($object))
{
foreach ($object as $likes){
if(is_array($likes))
{
foreach ( $likes as $data ){
if(is_array($data))
{
foreach ( $data as $id ){
if (is_numeric($id))
{
echo "$id".'<br />';
}
}
}
}
}
}
}
}
}
?>
Simplifying:
$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));
$user_ids = array();
foreach ($json->likes->data as $user) {
$user_ids[] = $user->id;
}
print implode('<br />', $user_ids);
Simplifying even more:
$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));
print implode('<br />', array_map(function ($user) {
return $user->id;
}, (array) $json->likes->data));
That's all! :)