Search code examples
phpmysqlmapboxmapbox-gl-draw

PHP JSON encode numerical array in MySQL


i try save and edit lines in Mapbox GL Draw, for this i use MySQL and PHP (requirements), and only save the coordinates in MySQL, but i make query and encode in JSON, program return this

"geometry": {
    "coordinates": "[[8.971375670640924,39.27952971962691],[9.019097533433808,39.29998983691581],[9.062012877672174,39.27554328682473],[9.125870909898737,39.28643899912291],[9.14097711107047,39.30742839737994],[9.178742614000214,39.30344355258791]]",
    "type": "LineString"
}

and i need the coords in numerical array, how this

"geometry": {
    "coordinates": [
        [
            9.06905,
            39.248296
        ],
        [
            9.111966,
            39.26212
        ],
        [
            9.135998,
            39.239256
        ],
        [
            9.039472,
            39.25596
        ],
        [
            9.042251,
            39.25373
        ]
    ],
    "type": "LineString"
}

the coords it´s in MySQL how JSON (longtext utf8mb4_bin), and query for 1 data is

while($row = mysqli_fetch_assoc($result_task)) {
    $ruta['features'][0]['geometry']['coordinates'] = $row['ruta'];
}

Solution

  • Based on the data that you show, ruta in the database is already JSON. Decode it before assigning to the array then encode it:

    while($row = mysqli_fetch_assoc($result_task)) {        
        $ruta['features'][0]['geometry']['coordinates'] = json_decode($row['ruta']);
    }
    $result = json_encode($ruta);
    

    In this example there is no need for the loop, just run mysqli_fetch_assoc.