1

I have a small but weird problem while encoding php arrays to json.

I need to prevent array() from adding double quotes around specific values.

Here is the php array:

$coordinates="[".$row["lat"].",".$row["lng"]."]";  
$egUser=array(              

            "geometry"=>array(
                "type"=>"$type",
                "coordinates"=>$coordinates                 
        ),

            "type2"=>"$type2",
            "id"=>$id
        );
$arrayjson[]=$egUser;   

Wich return the following json with json_encode :

var member = {
"type": "FeatureCollection",
"features": [{
    "geometry": {
        "type": "Point",
        "coordinates": "[46.004028,5.040131]"
    },
    "type2": "Feature",
    "id": "39740"
}]

};

As you can see the coordinates are wrapped inside double quote >

"coordinates": "[46.004028,5.040131]"

How do I get rid of these quotes ? I need to have the following instead >

"coordinates": [46.004028,5.040131]

I'm a bit confuse so any help is welcome :) Thank you !

Olivier
  • 54
  • 1
  • 8

1 Answers1

3

Thats because $coordinates is of type String.

$coordinates="[".$row["lat"].",".$row["lng"]."]";

Create $coordinates like this

$coordinates = array($row["lat"],$row["lng"]);
Josnidhin
  • 12,469
  • 9
  • 42
  • 61
  • 2
    +1, also note that if you are using PHP 5.4+ you can use the shorthand array syntax to declare it exactly as you would in Javascript: `$coordinates = [$row["lat"], $row["lng"]];` – DaveRandom Jun 13 '12 at 10:21
  • Indeed, json_encode tries to determinate the type, since in the main example the type is string, it adds quotes around it, if you apply what is just said above, you'll have the array you are looking for – PEM Jun 13 '12 at 10:21
  • it returns `"coordinates": ["46.004028", "5.040131"]`, now I've got quotes around the numbers ! – Olivier Jun 13 '12 at 10:25
  • that means $row["lat"] and $row["lng"] is also returning string convert into float and the quotes will be gone http://php.net/manual/en/function.floatval.php – Josnidhin Jun 13 '12 at 10:27
  • 2
    @Olivier Try `$coordinates = array((float) $row["lat"], (float) $row["lng"]);` – DaveRandom Jun 13 '12 at 10:28
  • Thanks! I tried with intval() but (float) is the correct one :) – Olivier Jun 13 '12 at 10:30