Home > Software design >  Get data from JSON file in php (not nested items)
Get data from JSON file in php (not nested items)

Time:10-08

I have a JSON file like this:

{"long_name":"Ukraine","short_name":"ukr","center_lat":"48.379433","center_lng":"31.16558","sw_lat":"44.2924","sw_lng":"22.137159","ne_lat":"52.3793713","ne_lng":"40.2204802"},{"long_name":"Zimbabwe","short_name":"zwe","center_lat":"-19.015438","center_lng":"29.154857","sw_lat":"-22.4219117","sw_lng":"25.237368","ne_lat":"-15.6093188","ne_lng":"33.068236"}

In PHP I want to get country bounds by country short_name

$area = cot_import('area', 'G', 'ALP');

//short_name from json, for example it is 'ukr'

Obvious:

$str = file_get_contents('/countries.json');

$json = json_decode($str);

And here - how can I parse json to get

    $sw_lat = 44.2924;
    $ne_lat = 52.3793713;
    $sw_lng = 22.137159;
    $ne_lng = 40.2204802;

PS. To be more specific - I always have only one $area, all I want is to parse json, find a string by its short_name and get 4 coordinates variables.

CodePudding user response:

You're on the right path! You could simplify this even more by having the function return $country when it is found instead of constructing a new array.

$countries = json_decode(file_get_contents('countries.json'), true);

function get_country_bounds($short_code, $countries)
{
    foreach ($countries as $country) {
        if (strtolower($country['short_name']) === strtolower($short_code)) {
            return [
                'sw_lat' => $country['sw_lat'],
                'ne_lat' => $country['ne_lat'],
                'sw_lng' => $country['sw_lng'],
                'ne_lng' => $country['ne_lng']
            ];
        }
    }
}

$bounds = get_country_bounds('ukr', $countries);

var_dump($bounds);

Yields

array(4) {
    ["sw_lat"]=>
    string(7) "44.2924"
    ["ne_lat"]=>
    string(10) "52.3793713"
    ["sw_lng"]=>
    string(9) "22.137159"
    ["ne_lng"]=>
    string(10) "40.2204802"
  }
  •  Tags:  
  • php
  • Related