-1

So I am working in PHP and I am trying to create a routine to search this huge GeoJSON array for a given country name, which would then return the associated co-ordinates for that country upon a match.

For example here, if I were to search for the value "Bahamas" I would be able to retrieve 'coordinates' directly or even where it lies under 'features'.

Array
    (
        [type] => FeatureCollection
        [features] => Array
            (
                [0] => Array
                (
                    [type] => Feature
                    [properties] => Array
                        (
                            [name] => Bahamas
                            [iso_a2] => BS
                            [iso_a3] => BHS
                            [iso_n3] => 044
                        )

                    [geometry] => Array
                        (
                            [type] => MultiPolygon
                            [coordinates] => Array
                                (
                                    [0] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [0] => -77.53466
                                                            [1] => 23.75975
                                                        )

                                                    [1] => Array
                                                        (
                                                            [0] => -77.78
                                                            [1] => 23.71
                                                        ) etc....

I have parsed the JSON file in PHP and tried a few methods but have really hit a brick wall at this point...

<?php
        
    $contents = file_get_contents('countryBorders.geo.json');

    $contents = json_decode($contents, true);
    
?>

1 Answers1

0
What about

<?php
$array = [
    'features' => [
        0 => [
            'properties' => [
                'name' => 'Bahamas',
            ],
            'geometry' => [
                'coordinates' => ['found']
            ]
        ],
        1 => [
            'properties' => [
                'name' => 'Barbados',
            ],
            'geometry' => [
                'coordinates' => []
            ]
        ],
    ]
];
foreach ($array['features'] as $feature) {
    if ('Bahamas' === $feature['properties']['name'] ?? false) {
        var_dump($feature['geometry']['coordinates'] ?? []);
        break;
    }
}

You might want to pre-compute an index if you need to get multiple places (features) in a row.

MoVod
  • 1,083
  • 10
  • 10