I have a file test.json see below
[
{
"ID": "01AD003",
"Name": "ST. FRANCIS RIVER AT OUTLET OF GLASIER LAKE",
"Latitude": 47.20661,
"Longitude": -68.95694,
"Prov": "NB",
"Timezone": "UTC-04:00"
},
{
"ID": "01AD004",
"Name": "SAINT JOHN RIVER AT EDMUNDSTON",
"Latitude": 47.36078,
"Longitude": -68.32489,
"Prov": "NB",
"Timezone": "UTC-04:00"
},
{
"ID": "01AF002",
"Name": "SAINT JOHN RIVER AT GRAND FALLS",
"Latitude": 47.03889,
"Longitude": -67.73972,
"Prov": "NB",
"Timezone": "UTC-04:00"
}
]
I am trying to search this file based on the ID element and return the Latitude and Longitude using php
I have tried adding a string local:
function getLatLong($id)
{
$str = file_get_contents("./hydrometric_StationList.json");
$json = json_decode($str);
foreach($json->local as $item)
{
if($item->ID == $id)
{
return $item->Latitude.",".$item.Latitude;
}
}
}
You can use true as the second parameter on json_decode to decode it as assositive array instead of an object. You can do a simple foreach loop like:
function getLatLong($id)
{
$str = file_get_contents("./hydrometric_StationList.json");
$json = json_decode($str, true);
foreach($json as $item)
{
if($item['ID'] == $id)
{
return $item['Latitude'].",".$item['Latitude'];
}
}
}
echo getLatLong("01AF002"); will result to: 47.03889,47.03889
There are a couple of mistakes in your code.
In your foreach() you have $json->local, but local isn't in the data. Just remove the ->local part.
In the return you have $item.Latitude, which both shouldn't be a . and is returning the latitude again, so change this to $item->Longitude...
function getLatLong($id)
{
$str = file_get_contents("./hydrometric_StationList.json");
$json = json_decode($str);
foreach($json->local as $item)
{
if($item->ID == $id)
{
return $item->Latitude.",".$item->Longitude;
}
}
}
Related
This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>
I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>
I;m trying to get data from a website using the following code:
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
var_dump($content);
$json = json_decode($content, true);
var_dump($json);
for ($idx = 0; $idx < count($json); $idx++) {
$obj = (Array)$json[$idx];
echo 'result' . $obj["name"];
}
?>
Which is getting me this result:
string(0) "" NULL
<?php
$url = 'http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=4798';
$content = file_get_contents($url);
echo "<pre>";
//print_r($content);
$data = json_decode($content);
print_r($data); //Show the json decoded data comes form $url
##Parse this array {$data} using foreach loop as your use
?>
There are no numeric keys in the json returned from the url you posted in your question. So iterating through the associative array with numeric keys returns nothing.
This is the structure of the json you are working with:
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_oldschool/5122_obj_big.gif?id=4798",
"id": 4798,
"type": "Default",
"typeIcon": "http://www.runescape.com/img/categories/Default",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow... ouch.",
"current": {
"trend": "neutral",
"price": 529
},
"today": {
"trend": "neutral",
"price": 0
},
"members": "true",
"day30": {
"trend": "negative",
"change": "-9.0%"
},
"day90": {
"trend": "negative",
"change": "-20.0%"
},
"day180": {
"trend": "negative",
"change": "-31.0%"
}
}
}
Try accessing $json["item"]. That should give you something more meaningful to work with. If you want to iterate over the key/value pairs in the item, use a foreach loop:
foreach($json["item"] as $key => $value) {
echo $key . ":";
print_r($value);
}
i have an array like this JSON Example .I'm trying to replace the numeric key ..."conn":{"1":{"... with string key such as "node".
FOR EXAMPLE i want to create this:
{
"Level": [
{
"main": "472321514",
"main_lat": "39.1057579",
"main_lon": "26.5451331",
"conn": {
"node": {
"id": "599416249",
"coords": {
"lat": "39.1055889",
"lon": "26.5452403"
},
"distance": 0.0209442235276
},...
Before json encoding my script is:
foreach ($ways as $w){
$nd=$w->nd;
foreach ($nd as $w2){
$nodes_Array[]=(string)$w2->attributes()->ref;
}
for($ww=0;$ww<count($nodes_Array);$ww++){
$nodes_Array2[$bb]['main'] = $nodes_Array[$ww];
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['main']){
$nodes_Array2[$bb]['main_lat']= $node_content[$gg]['lat'];
$nodes_Array2[$bb]['main_lon']= $node_content[$gg]['lon'];
}
}
$nodes_Array2[$bb]['conn'] = array_diff($nodes_Array, array($nodes_Array[$ww]));
for($cc=0;$cc<count($nodes_Array2[$bb]['conn']);$cc++){
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['conn'][$cc]){
$nodes_Array2[$bb]['conn'][$cc]=Array(
'id'=>$node_content[$gg]['id'],
'coords'=>Array(
'lat'=>$node_content[$gg]['lat'],
'lon'=>$node_content[$gg]['lon'],
),
'distance'=>distance($nodes_Array2[$bb]['main_lat'],$nodes_Array2[$bb]['main_lon'],$node_content[$gg]['lat'],$node_content[$gg]['lon'],"K"),
);
}
}
}
$bb++;
}
unset($nodes_Array);
}
I am attempting to work with JSON in PHP and I was wondering if someone could help me out getting me to the $events=>$url when the information is returned from json_decode. What is the variable path. There are a number of looping record in the return data and I am using something like:
$data = json_decode($feeds,true);
foreach($data as $item=>$events) {
$date = $events=>$month.'/'.$events=>$day.'/'.$events=>$year;
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$item["title"].'</span><br />'.$item["details"].'</li>';
}
Here is the JSON sample (yes, I know it is incomplete)
{
"month": 5,
"year": 2013,
"events": [
{
"url": "http://www.engin.umich.edu/college/about/cal/events/2013/may/shavuot-ends",
"id": "shavuot-ends",
"month": 5,
"year": 2013,
"day": 16,
"startTime": "1:42",
"endTime": "1:42",
"hideTime": "true",
"deadline": "true",
"am_pm": "pm",
"am_pm_start": "pm",
"am_pm_end": "pm",
"title": "Shavuot ends",
"location": "",
"details": "Shavuot runs from May 14 to May 16.",
"host": "Michigan Engineering",
"event_type": "Holiday",
"image": {
"src": "http://www.engin.umich.edu/++resource++umich_images/default_event.jpg",
"alt": "Shavuot ends"
}
},...
You have mixed up your -> and => operators. Try like this:
$data = json_decode($feeds,true);
foreach($data['events'] as $event) {
$date = $event['month'].'/'.$event['day'].'/'.$event['year'];
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$event["title"].'</span><br />'.$event["details"].'</li>';
}
$data['events']['url']
The array is multidimensional.
foreach($data as $key=>$item) {
if($key=='events') {
$url = $item['url'];
}
}
or
foreach($data['events'] as $key=>$item) {
if($key=='url') {
$url = $item;
}
}
try this:
$data = json_decode($feeds);
$eventsHtml = "";
foreach($data->events as $event ) {
$date = $data->month.'/'.$event->day.'/'.$data=>year;
$eventsHtml .='<li><span class="engindate">'.$date.
'</span><br /><span class="source">'.
$event=>title.
'</span><br /><a href="'.$event=>url.'">'.
$event->details.'</a></li>';
}
You have an object "data". This has a member "month", so this is $data->month
It has a member "events" which is an array. The first event is $data->events[0]. If you iterate with a foreach, this is foreach($data->events as $event ) { having $event as the one event.
Basic errors:
$events=>$month // is inproper syntax
foreach($data as $item=>$events) {
..
$events.= // this would overwrite the iterator variable above ??