如何优化PHP脚本以返回指定父子结构的JSON?
问题描述
我希望调整PHP脚本,使其返回带有父子层级的特定JSON结构。我已在Stack Overflow搜索相关问题,但未找到合适的解决方案。
我的数据库中有一张名为tbl_countries的表,结构如下:
id | countryID | country | city ----------------------------------------- 1 | 1 | Greece | Athens 2 | 1 | Greece | Thessalonica 3 | 2 | Italy | Rome 4 | 2 | Italy | Milan
我期望返回的JSON结构如下:
[{ "id": 1, "text": "Greece", "children": [{ "id": "Athens", "text": "Athens" }, { "id": "Thessalonica", "text": "Thessalonica" }] }, { "id": 2, "text": "Italy", "children": [{ "id": "Milan", "text": "Milan" }, { "id": "Rome", "text": "Rome" }] }]
以下是我当前的PHP脚本,它能正确返回数据但不符合目标结构:
include 'config.php'; $stmt = $mysqli -> prepare('SELECT countryID, country, city FROM tbl_countries'); $stmt -> execute(); $stmt -> store_result(); $stmt -> bind_result($countryID, $country, $city); $json = array(); while ($stmt -> fetch()) { $json[] = array("id" => $countryID, "text" => $country, "children" => [array("id" => $city, "text" => $city)]); } header('Content-Type: application/json'); print_r(json_encode($json, JSON_UNESCAPED_UNICODE));
请问如何优化该PHP脚本,使其返回上述指定的JSON结构?
解决方案
你的问题核心是每一行数据都生成了独立的国家对象,没有将同一国家的城市合并到同一个children数组中。可以通过分组收集的方式优化:
优化后的PHP脚本
include 'config.php'; $stmt = $mysqli->prepare('SELECT countryID, country, city FROM tbl_countries'); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($countryID, $country, $city); // 临时数组,用countryID作为键实现分组 $temp = []; while ($stmt->fetch()) { // 若当前国家未初始化,先创建父结构 if (!isset($temp[$countryID])) { $temp[$countryID] = [ "id" => $countryID, "text" => $country, "children" => [] ]; } // 将当前城市追加到对应国家的children数组 $temp[$countryID]["children"][] = [ "id" => $city, "text" => $city ]; } // 转换为索引数组,匹配目标JSON结构 $json = array_values($temp); header('Content-Type: application/json'); echo json_encode($json, JSON_UNESCAPED_UNICODE);
关键说明
- 用
$temp数组以countryID为键,确保同一个国家只生成一次父对象; - 循环时判断国家是否已存在,不存在则初始化父结构,存在则直接追加城市;
- 最后用
array_values()将关联数组转为索引数组,避免JSON中出现多余键名。
内容的提问来源于stack exchange,提问作者Michel Xavier
相关产品推荐
相关产品推荐

