How to transform string into array

Asked

Viewed 447 times

-1

I get a result that way:

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

I need to turn into this shape:

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

Thanks in advance.

1 answer

2


You can use basic string handling functions.

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

Then use the function explode() to subdivide this string into an array, and with the help of a foreach add items to the final array with 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]);
}

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)
  • Good Afternoon. I appreciate the help. sorry but I still don’t understand very well

  • I will edit the answer with a complete solution for you to see.

  • Ruhan can also remove {"area":"

  • @Carlosalexandrerramos did not understand, how to remove the area?

  • Good afternoon, my lords. I am receiving an array: { "lat": "[{"area":"-22.88975203013098", "lng": "-43.12695211119432" }, How to retreat {"area":"

  • To remove any part of your string use the str_replace function, in the first parameter you must pass which part of the string you want to rewrite, in the second you want to rewrite (in this case an empty string), and finally the string itself. For example: str_replace('area', '', $suaString);

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.