1.表结构
2.展示效果
[ { "id": "1", "name": "中国", "parent": "0", "child": [ { "id": "2", "name": "江苏", "parent": "1", "child": [ { "id": "3", "name": "苏州", "parent": "2", "child": [ { "id": "4", "name": "昆山", "parent": "3" } ] } ] } ] }, { "id": "5", "name": "美国", "parent": "0", "child": [ { "id": "6", "name": "加利福尼亚", "parent": "5", "child": [ { "id": "7", "name": "洛杉矶", "parent": "6" } ] } ] } ]
3.代码实现
<?php
$sql = "SELECT id, name, parent FROM YourTable";
$countrys = $conn->query($sql);
// 第一次查询,找出根节点
foreach ($countrys as $curr){
if($curr['parent'] == 0){
$r[] = $this->child($curr,$countrys);
}
}
// 查询当前节点的子节点
function child($curr,$countrys){
foreach ($countrys as $key => $country){
if($curr['id'] == $country['parent']){
$curr['child'][] = child($country,$countrys);
}
}
return $curr;
}
echo json_encode($r);
#结果
#[{"id":"1","name":"\u4e2d\u56fd","parent":"0","child":[{"id":"2","name":"\u6c5f\u82cf","parent":"1","child":[{"id":"3","name":"\u82cf\u5dde","parent":"2","child":[{"id":"4","name":"\u6606\u5c71","parent":"3"}]}]}]},{"id":"5","name":"\u7f8e\u56fd","parent":"0","child":[{"id":"6","name":"\u52a0\u5229\u798f\u5c3c\u4e9a","parent":"5","child":[{"id":"7","name":"\u6d1b\u6749\u77f6","parent":"6"}]}]}]
小结:这种小功能可用于菜单、类型的查询,在项目中可以用缓存保存