R.Merritt
R.Merritt

Reputation: 477

searching a json file

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

}

Upvotes: 0

Views: 60

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57141

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

}

Upvotes: 1

Eddie
Eddie

Reputation: 26854

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

Upvotes: 1

Related Questions