Tomas Lucena Tomas Lucena - 1 year ago 111
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:


Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download