Converting string to two dimensional array in php

Tags: ,



just would like to ask how can I convert the string into two dimensional array in php. Please refer my sample code below.

$coordinates = "9.499819 123.920318,9.490845 123.916563,9.484644 123.922292,9.49148 123.931519,9.499755 123.925683,9.499819 123.920318";

I want to convert above string into below array and assigned it to variable.

$polygon = array(array('lat' => 9.499819,'lng'=>123.920318),
               array('lat' => 9.490845,'lng'=>123.916563),
              array('lat' => 9.484644,'lng'=>123.922292),
               array('lat' => 9.49148,'lng'=>123.931519),
              array('lat' => 9.499755,'lng'=>123.925683),
                array('lat' => 9.499819,'lng'=>123.920318)
              );

Answer

For a new contributor, a solution with foreach is easier to understand in my opinion. The steps are commented in the code.

$coordinates = "9.499819 123.920318,9.490845 123.916563,9.484644 123.922292,9.49148 123.931519,9.499755 123.925683,9.499819 123.920318";

$polygon = explode(',',$coordinates);
/*
array (
  0 => "9.499819 123.920318",
  1 => "9.490845 123.916563",
*/

foreach($polygon as $index => $latLng){
  //The element $latLng is split into two variables with list and explode.
  list($lat,$lng) = explode(' ',$latLng);

  //The elements are replaced by a new array with the variables $lat and $lng as float
  $polygon[$index] = ['lat' => (float)$lat, 'lng' => (float)$lng];
}

//test output
echo '<pre>';
var_export($polygon);

output:

array (
  0 => 
  array (
    'lat' => 9.499819,
    'lng' => 123.920318,
  ),
  1 => 
  array (
    'lat' => 9.490845,
    'lng' => 123.916563,
  ),
  2 => 
  array (
    'lat' => 9.484644,
    'lng' => 123.922292,
  ),
  3 => 
  array (
    'lat' => 9.49148,
    'lng' => 123.931519,
  ),
  4 => 
  array (
    'lat' => 9.499755,
    'lng' => 123.925683,
  ),
  5 => 
  array (
    'lat' => 9.499819,
    'lng' => 123.920318,
  ),
) 


Source: stackoverflow