首页 > 解决方案 > PHP JSON在MySQL中编码数字数组

问题描述

我尝试在 Mapbox GL Draw 中保存和编辑行,为此我使用 MySQL 和 PHP(要求),并且只将坐标保存在 MySQL 中,但我在 JSON 中进行查询和编码,程序返回这个

"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"
}

我需要数值数组中的坐标,这是怎么回事

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

它在 MySQL 中的坐标如何 JSON (longtext utf8mb4_bin) 和查询 1 个数据是

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

标签: phpmysqlmapboxmapbox-gl-draw

解决方案


根据您显示的数据,ruta数据库中已经是 JSON。在分配给数组之前对其进行解码,然后对其进行编码:

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

在此示例中,不需要循环,只需运行mysqli_fetch_assoc.


推荐阅读