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)
);
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,
),
)
Add 2022-03-04:
This one-liner with preg_match_all already returns the complete result, but with additional numeric keys.
preg_match_all('~(?<lat>[0-9.]+) (?<lng>[0-9.]+),?~', $coordinates, $match,PREG_SET_ORDER);
array_map can be used to remove the superfluous values.
$polygon = array_map(
function($row){return ['lat' => $row['lat'],'lng' => $row['lng']];},
$match
);