Tomas Lucena Tomas Lucena - 4 months ago 19x
JSON Question

PHP - JSON_ENCODE Number converted to string. How to fix it?

I have the following variable with some coordinates from google maps:

$coordinates = '(22.2819939, 114.15444100000002)';

So to separate them I did the following:

$coor = explode(',',str_replace(array('(',')'),'',$coordinates));

Now I need to send this coordinates to an API in the following format:

$message = array("location"=>array($coor[1],$coor[0]));

I must send this in json so I encode the array but I am getting the coordinates as strings and not as number:

$toSend = json_encode($message);
result-> {"location":["114.15444100000002","22.2819939"]}

How can I avoid json to take the coordinates as string and take them as number instead?

I need this result:



You'll need to convert them from string to float. So we simply map the array with a float conversion

$coor = array_map(`floatval`, $coor);