With Treat a string transforming into an array [duplicate]

0

I get a string from the database this way:

POLYGON((-22.886145457836463 -43.118764097835, -22.88643210096987 -43.118324215556555, -22.886694032959 -43.117846782351904, -22.886763222456636 -43.11767512097496, -22.886782990878046 -43.117605383540564, -22.886886775043237 -43.11763757004875, -22.887133879879073 -43.11891966595787, -22.88630360584699 -43.11942392125267, -22.886115805063966 -43.118823106433325, -22.886145457836463 -43.118764097835))

I need only the coordinates between parentheses:

-22.886145457836463 -43.118764097835, -22.88643210096987 -43.118324215556555, -22.886694032959 -43.117846782351904, -22.886763222456636 -43.11767512097496, -22.886782990878046 -43.117605383540564, -22.886886775043237 -43.11763757004875, -22.887133879879073 -43.11891966595787, -22.88630360584699 -43.11942392125267, -22.886115805063966 -43.118823106433325, -22.886145457836463 -43.118764097835

With the Coordinates, I need to create an array:

{lat: -22.886145457836463, lng: -43.118764097835},
{lat: -22.88643210096987, lng: -43.118324215556555},
{lat: -22.886694032959, lng: -43.117846782351904}

and etc ...

How do I do it?

    
asked by anonymous 03.10.2017 / 00:43

1 answer

1

To extract this information, you need to work with 3 functions that are str_replace to remove what is unnecessary and then use explode creating a array using the spaces between the values and trim to remove the start and end spaces.

After this, create a step by step and do the new array from that having the keys for and lat as requested in your question, minimum example :

<?php

$str = 'POLYGON((-22.886145457836463 -43.118764097835, -22.88643210096987
                -43.118324215556555, -22.886694032959 -43.117846782351904,
                -22.886763222456636 -43.11767512097496, -22.886782990878046
                -43.117605383540564, -22.886886775043237 -43.11763757004875,
                -22.887133879879073 -43.11891966595787, -22.88630360584699
                -43.11942392125267, -22.886115805063966 -43.118823106433325,
                -22.886145457836463 -43.118764097835))';

function array_final($str)
{
    $str = str_replace(['POLYGON','((','))'], [''], $str);
    $str = explode(" ", trim($str));
    $arrays = [];
    for($i = 0; $i < count($str); $i += 2)
    {
        $arrays[] = ['lat' => $str[$i], 'lng' => $str[$i+1]];
    }
    return $arrays;
}

var_dump(array_final($str));

Online Sample

Note: Framework which is written in , will not solve all problems, particularly private ones, we often need to brush code to create certain solutions, which is in this case specific.

03.10.2017 / 01:03