0

I want to be able to navigate to the coordinates within the following table:

{
  "type": "Polygon",
  "coordinates": [
    [
      [
        37.02255983,
        -1.43654556
      ],
      [
        37.08298464,
        -1.41777117
      ],
      [
        37.03893607,
        -1.44272341
      ],
      [
        36.96500169,
        -1.48081985
      ],
      [
        36.91303988,
        -1.47429887
      ]
    ]
  ]
}

I am pulling this data from a database and my first level looping results in the above object array. My first level code is as follows:

<?php
    $locations = \App\Model::all();
    foreach ($locations as $key=>$location)
    {
      $polygonXML = $location['polygon'];
      dd($polygonXML);
    }
?>

I want to end up with the coordinate key.

Skully
  • 2,882
  • 3
  • 20
  • 31
Kevin Otieno
  • 55
  • 1
  • 10

1 Answers1

0

The data you have is in the format of JSON, so you must first convert it to an iterable object in PHP using json_decode(), this converts it to an array and then a simple foreach loop can be used to go through every entry in the "coordinates" table.

<?php

// Encode your JSON data from where it is coming from.
$data = json_decode('{
  "type": "Polygon",
  "coordinates": [
    [
      [
        37.02255983,
        -1.43654556
      ],
      [
        37.08298464,
        -1.41777117
      ],
      [
        37.03893607,
        -1.44272341
      ],
      [
        36.96500169,
        -1.48081985
      ],
      [
        36.91303988,
        -1.47429887
      ]
    ]
  ]
}', true);

foreach($data["coordinates"][0] as $coodinate)
{
    var_dump($coodinate[0] . ", " . $coodinate[1]);
}

Output:

string(24) "37.02255983, -1.43654556"
string(24) "37.08298464, -1.41777117"
string(24) "37.03893607, -1.44272341"
string(24) "36.96500169, -1.48081985"
string(24) "36.91303988, -1.47429887"
Skully
  • 2,882
  • 3
  • 20
  • 31