You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MySQL查询结果转换为指定JSON结构以替换JS端模拟数据

实现方案

步骤1:PHP端转换数据结构

你可以在拿到数据库查询结果后,直接在PHP层组装成目标格式,再转成JSON字符串传给前端:

// 此处为你执行SQL查询的逻辑,假设最终拿到的结果集为数组 $dbResults,数组内每个元素为查询返回的stdClass对象
$storesStructure = [
    'type' => 'FeatureCollection',
    'features' => []
];

foreach ($dbResults as $storeItem) {
    $storesStructure['features'][] = [
        'type' => 'Feature',
        'geometry' => [
            'type' => 'Point',
            // 注意:GeoJSON规范要求坐标顺序为 [经度, 纬度],不要写反
            'coordinates' => [
                (float)$storeItem->lng,
                (float)$storeItem->lat
            ]
        ],
        'properties' => [
            // 若logo为相对路径,可自行拼接站点域名前缀
            'storeImage' => $storeItem->logo,
            'storeName' => $storeItem->name,
            'phoneFormatted' => $storeItem->phone,
            'address' => $storeItem->address,
            'city' => $storeItem->city,
            'country' => $storeItem->country,
            'postalCode' => $storeItem->zip,
            'state' => $storeItem->state
        ]
    ];
}

// 转换为JSON字符串,避免中文和斜杠被转义
$storesJson = json_encode($storesStructure, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

步骤2:输出到前端页面

在你的HTML模板中,直接把生成的JSON字符串输出到JavaScript变量位置即可,替换你原来的模拟对象:

<script type="text/javascript">
const stores = <?php echo $storesJson; ?>;
</script>

注意事项

  • 若需要对手机号做格式调整(比如把555-555-5555转换为(555) 555-5555的格式),可以在PHP层新增格式化函数处理$storeItem->phone后再赋值
  • 如果仅查询到单条门店数据,不需要循环,直接把单条数据组装后塞进features数组即可
  • 若后续回到Joomla环境,该逻辑无需大改,仅需把数据库查询部分替换为Joomla框架自带的数据库操作方法即可正常运行

内容的提问来源于stack exchange,提问作者Geoff_S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:09:03