How to transform string into array

-1

I get a result like this:

"POLYGON((-22.886145457836463 -43.118764097835, -22.88643210096987 -43.118324215556555, -22.886694032959 -43.117846782351904, -22.886763222456636 -43.11767512097))"

I need to transform this way:

lat=> -22.886145457836463, lng=>-43.118764097835,
lat=> -22.88643210096987, lng=>-43.118324215556555,
lat=> -22.886694032959, lng=>-43.117846782351904,
lat=> -22.886763222456636, lng=>-43.117846782351907

Thank you in advance.

    
asked by anonymous 07.09.2017 / 22:28

1 answer

2

You can use basic string manipulation functions.

Use the str_replace() function to remove the parentheses, and some undesirable spaces after the comma, leaving only the values.

Then use the explode() function to subdivide this string into an array, and with the help of foreach add the items to the final array with the values:

$latLongString = "POLYGON((-22.886145457836463 -43.118764097835, -22.88643210096987 -43.118324215556555,-22.886694032959 -43.117846782351904, -22.886763222456636 -43.11767512097))";

$latLongString = str_replace(["POLYGON((","))"], "", $latLongString); // remover os parenteses deixando somente os valores;
$latLongString = str_replace(", ", ",", $latLongString); // remover os espaços depois das virgulas;

$arrayLatLong = array();

$valores = explode(",",$latLongString);
foreach($valores as $subVal){
  $latLong = explode(" ",$subVal);
  $arrayLatLong[]=array("lat"=> $latLong[0],"lng"=>$latLong[1]);
}

In this way your output will be an array with this format:

array (size=4)
  0 =>
    array (size=2)
      'lat' => string '-22.886145457836463' (length=19)
      'lng' => string '-43.118764097835' (length=16)
  1 =>
    array (size=2)
      'lat' => string '-22.88643210096987' (length=18)
      'lng' => string '-43.118324215556555' (length=19)
  2 =>
    array (size=2)
      'lat' => string '-22.886694032959' (length=16)
      'lng' => string '-43.117846782351904' (length=19)
  3 =>
    array (size=2)
      'lat' => string '-22.886763222456636' (length=19)
      'lng' => string '-43.11767512097' (length=15)
    
08.09.2017 / 19:37