'Split and parse a string to create an array of associative arrays

How can I convert the following string into two dimensional array?

$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 separate pairs of values using the commas, then separate each pair by their delimiting space to form associative rows containing float-type values.

Desired Output:

$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)
);


Solution 1:[1]

By making iterated calls of sscanf(), you can dictate the data type of the parsed values and push the values into the result array.

Code: (Demo)

$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";

foreach (explode(',', $coordinates) as $i => $latLng) {
    sscanf($latLng, '%f %f', $result[$i]['lat'], $result[$i]['lng']);
};
var_export($result);

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,
  ),
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mickmackusa