如何使用 PHP 和 MySQL 创建 JSON 嵌套子父树(PDO 方法)
Posted
技术标签:
【中文标题】如何使用 PHP 和 MySQL 创建 JSON 嵌套子父树(PDO 方法)【英文标题】:How to create JSON nested child parent tree with PHP and MySQL(PDO method) 【发布时间】:2016-01-24 08:42:27 【问题描述】:我正在尝试使用 php 和 mysql 构建嵌套的父子 JSON 树。 我的目标是从我的 MySQL DB 创建一个 JSON 树,并使用 AngularJS 在前端显示一个树。创建树很重要。 我的数据库结构是:
╔═══════╦═══════════════════╦═════════╗ ║ id ║ 姓名 ║parent_id║ ╠═══════╬═══════════════════╬═════════╣ ║ 1 ║ 家长 ║ 0 ║ ║ 2 ║ 儿童 1 ║ 1 ║ ║ 3 ║ 儿童 2 ║ 1 ║ ║ 4 ║ Grand Child-1 ║ 2 ║ ║ 5 ║ Grand Child-2 ║ 2 ║ ║ 6 ║ Grand Child-3 ║ 3 ║ ║ 7 ║ Grand Child-4 ║ 3 ║ ╚═══════╩═══════════════════╩═════════╝我需要树看起来像:
父母 |--儿童-1 | |--孙子-1 | |_ 孙子-2 |--Child-2 | |--孙子-3 | |_ Grand Child-4
我做了这样的事情:
function hasChild($id)
$sql = "SELECT count(*) FROM `myTable` WHERE parent_id=".$id;
$stmt = $this->db->prepare($sql);
$stmt->execute($a);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $row[0] > 0 ? true : false;
//function hasChild($id)
// create an index on id
$index = array();
foreach($rows as $i =>$row)
if (hasChild($i))
$index[$row['id']] = $row;
// build the tree
foreach($index as $id => $indexRow)
if ($id === 1) continue;
$parent = $indexRow['parent_id'];
$index[$parent]['children'][] = $indexRow;
unset($indexRow);
echo json_encode($index);
但它显然没有给我正确的 json 树 :( 我已经查看了嵌套 json 和数组解决方案,但有些东西对我来说并没有点击,所以我希望有人可以帮助我解决这个问题。我可以使用另一种方式,只要我可以拥有相同/相似的功能。 希望我能够很好地描述这种情况,但如果您需要更多数据,请告诉我。 提前致谢!
【问题讨论】:
【参考方案1】:$a
未定义。您也没有在查询中使用任何占位符,所以我认为这会失败。
试试:
function hasChild($id)
$sql = "SELECT count(*) as da_count FROM `myTable` WHERE parent_id = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['da_count'] > 0 ? true : false;
//function hasChild($id)
关于准备好的语句的更长的文章:http://php.net/manual/en/pdo.prepared-statements.php。
【讨论】:
感谢您的回复,但我没有使用准备好的语句,所以我刚刚定义了$a = array();
,我根据您的建议更改了我的代码,但它仍然无法正常工作:(
您尝试过我的代码还是尝试使用空数组?您正在使用准备好的语句而不是参数化查询。
对不起,我忘了更新你。是的,您的代码有效,并且由于框架纤薄而出现问题。非常感谢。【参考方案2】:
几天前我也遇到了同样的问题,所以找到了另一种方法来解决这个问题
邮递员提前回复
"Status": 200,
"Data":
"MyAssetsList": [
"AssetsId": 15,
"UserCredentialId": 7,
"NickName": "jals",
"EquipmentId": "BO_15",
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"MakeId": 1,
"OEMName": "JCB",
"ModelId": 1,
"ModelName": "EX1235",
"YearOfPurchase": 2022,
"OtherOEMName": "rw",
"OtherModelName": 0,
"MetricId": 1,
"Capacity": "1.000 Kg",
"EquipmentAge": "2 Months",
"ProcessCompletionPercentage": 100
,
"AssetsId": 14,
"UserCredentialId": 7,
"NickName": "jal",
"EquipmentId": "",
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"MakeId": 1,
"OEMName": "JCB",
"ModelId": 1,
"ModelName": "EX1235",
"YearOfPurchase": 2022,
"OtherOEMName": "rw",
"OtherModelName": 0,
"MetricId": 1,
"Capacity": "1.000 Kg",
"EquipmentAge": "2 Months",
"ProcessCompletionPercentage": 33.33
,
"AssetsId": 13,
"UserCredentialId": 7,
"NickName": "rest",
"EquipmentId": "",
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"MakeId": 1,
"OEMName": "JCB",
"ModelId": 1,
"ModelName": "EX1235",
"YearOfPurchase": 2022,
"OtherOEMName": "rw",
"OtherModelName": 0,
"MetricId": 1,
"Capacity": "1.000 Kg",
"EquipmentAge": "2 Months",
"ProcessCompletionPercentage": 33.33
,
"AssetsId": 11,
"UserCredentialId": 7,
"NickName": "test",
"EquipmentId": "",
"EquipmentTypeId": 1,
"EquipmentTypeValue": "Excavator",
"MakeId": 1,
"OEMName": "JCB",
"ModelId": 1,
"ModelName": "EX1235",
"YearOfPurchase": 2022,
"OtherOEMName": 1,
"OtherModelName": 1,
"MetricId": 1,
"Capacity": "1.000 Kg",
"EquipmentAge": "2 Months",
"ProcessCompletionPercentage": 33.33
,
]
,
"Message":
"SuccessMessage": "My Asset Found Successfully"
邮递员在解决树结构问题后的响应很漂亮
"Status": 200,
"Data":
"MyAssets":
"AssetsId: 15":
"AssetId": 15,
"EquipmentType":
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"EquipmentMake":
"EquipmentMakeId": 1,
"EquipmentMakeValue": "JCB"
,
"EquipmentModel":
"EquipmentModelId": 1,
"EquipmentModelValue": "EX1235"
,
"EquipmentYearOfPurchase": 2022,
"EquipmentAge": "2 Months",
"OtherOEMName": "rw",
"OtherModelName": "rw",
"MetricType":
"MetricId": 1,
"Capacity": "1.000 Kg"
,
"ProcessCompletionPercentage": 100
,
"AssetsId: 14":
"AssetId": 14,
"EquipmentType":
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"EquipmentMake":
"EquipmentMakeId": 1,
"EquipmentMakeValue": "JCB"
,
"EquipmentModel":
"EquipmentModelId": 1,
"EquipmentModelValue": "EX1235"
,
"EquipmentYearOfPurchase": 2022,
"EquipmentAge": "2 Months",
"OtherOEMName": "rw",
"OtherModelName": "rw",
"MetricType":
"MetricId": 1,
"Capacity": "1.000 Kg"
,
"ProcessCompletionPercentage": 33.33
,
"AssetsId: 13":
"AssetId": 13,
"EquipmentType":
"EquipmentTypeId": 4,
"EquipmentTypeValue": "Backhoe",
"EquipmentMake":
"EquipmentMakeId": 1,
"EquipmentMakeValue": "JCB"
,
"EquipmentModel":
"EquipmentModelId": 1,
"EquipmentModelValue": "EX1235"
,
"EquipmentYearOfPurchase": 2022,
"EquipmentAge": "2 Months",
"OtherOEMName": "rw",
"OtherModelName": "rw",
"MetricType":
"MetricId": 1,
"Capacity": "1.000 Kg"
,
"ProcessCompletionPercentage": 33.33
,
"AssetsId: 11":
"AssetId": 11,
"EquipmentType":
"EquipmentTypeId": 1,
"EquipmentTypeValue": "Excavator",
"EquipmentMake":
"EquipmentMakeId": 1,
"EquipmentMakeValue": "JCB"
,
"EquipmentModel":
"EquipmentModelId": 1,
"EquipmentModelValue": "EX1235"
,
"EquipmentYearOfPurchase": 2022,
"EquipmentAge": "2 Months",
"OtherOEMName": 1,
"OtherModelName": 1,
"MetricType":
"MetricId": 1,
"Capacity": "1.000 Kg"
,
"ProcessCompletionPercentage": 33.33
,
,
"AssetImageFileReference": "https://localhost/e9/FileServer/AssetsImage/",
"AssetDocumentFileReference": "https://localhost/e9/FileServer/AssetsDocument/"
,
"Message":
"SuccessMessage": "My Asset Found Successfully"
用 PHP 代码创建类似上面的树结构
$A = array();
$Data->MyAssetsList = $ResultModel; // ResultModel Has query result of mysql
foreach($ResultModel as $R)
$A['MyAssets']["AssetsId: ".$R->AssetsId]['AssetId']= $R->AssetsId;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentTypeId"]= $R->EquipmentTypeId;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentTypeValue"]= $R->EquipmentTypeValue;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentMake"]['EquipmentMakeId']= $R->MakeId;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentMake"]['EquipmentMakeValue']= $R->OEMName;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentModel"]['EquipmentModelId']= $R->ModelId;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentModel"]['EquipmentModelValue']= $R->ModelName;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentYearOfPurchase"]= $R->YearOfPurchase;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["EquipmentAge"]= $R->EquipmentAge;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["OtherOEMName"]= $R->OtherOEMName;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["OtherModelName"]= $R->OtherOEMName;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["MetricType"]['MetricId']= $R->MetricId;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["MetricType"]['Capacity']= $R->Capacity;
$A['MyAssets']["AssetsId: ".$R->AssetsId]['EquipmentType']["ProcessCompletionPercentage"]= $R->ProcessCompletionPercentage;
$A['AssetImageFileReference'] = base_url(PATH_TO_FILESERVER_ASSETSIMAGE);
$A['AssetDocumentFileReference'] = base_url(PATH_TO_FILESERVER_ASSETSDOCUMENT);
【讨论】:
以上是关于如何使用 PHP 和 MySQL 创建 JSON 嵌套子父树(PDO 方法)的主要内容,如果未能解决你的问题,请参考以下文章
PHP 使用PHP,MySQL,XML和JSON创建基本Web服务
从 MySQL 结果和 PHP 为 D3.js 树创建分层 JSON?