我有一个数据库表,我必须从
建立一个UL列表。表格的设置如下 猫咪 parent-id(是任何父代的cat-id) 猫名 猫图片
我可以很容易地获得父母ID为“ 0”的根猫 但是对于我的一生,我不知道该怎么做,所以最终结果是
rootcat --childParent ---孩子
function cats(){
$sql = "SELECT * FROM `cats";
$cats;
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
if($cat["parent-id"] == "0"){
$cats[] = $cat["cat-name"];
}
}
}
mysqli_free_result($res);
mysqli_close($con);
return $cats;
}
答案 0 :(得分:0)
您可以像这样解析子类别,但是每次您检查父级具有哪些类别时,它都要求建立sql连接:
function cats(){
$sql = "SELECT * FROM `cats";
$cats;
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
if($cat["parent-id"] == "0"){
$cats[$key] = $cat["cat-name"];
$sql_subCategory = "SELECT * FROM cats where parent_id=". $cat["id"];
$res_sub = mysqli_query($con, $sql_subCategory);
if(mysqli_num_rows($res_sub) > 0){
while($cat_sub = $res_sub->fetch_array(MYSQLI_ASSOC)){
$cats[$cat["cat-name"]] = $cat_sub["cat-name"];
}
}
}
}
}
mysqli_free_result($res_sub);
mysqli_free_result($res);
mysqli_close($con);
return $cats;
}
那应该给你数组:
array(
'cat1' => 'Some Category',
'cat2' => array(
'sub1' => 'name',
),
);
答案 1 :(得分:0)
这就是我的结论,它是完全递归的
public function cats($id){
$con = mysqli_connect($this->vars["host"], $this->vars["user"], $this->vars["pass"], $this->vars["db"]);
$cats;
if(mysqli_connect_errno()){
print "START MYSQLI ERROR<br/>".
mysqli_connect_error() .
"<br/>ENDMYSQLI ERROR";
}else{
$cats[] = $this->child($id, $con);
mysqli_close($con);
return $cats;
}
}
function child($id,$con){
$sql = "SELECT * FROM `cats` WHERE `parent-id`= '".$id."'";
// print $sql ."<br/>";
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0){
while($cat = $res->fetch_array(MYSQLI_ASSOC)){
$cats[]["cat-name"] = $cat["cat-name"];
$sql_subCat = "SELECT * FROM `cats` WHERE `parent-id` = '".$cat["cat-id"]."'";
$res_sub = mysqli_query($con, $sql_subCat);
if(mysqli_num_rows($res_sub) > 0){
while($cat_sub = $res_sub->fetch_array(MYSQLI_ASSOC)){
$cats[$cat["cat-name"]][] = $cat_sub["cat-name"] ;
$cats[$cat["cat-name"]]= $this->child($cat["cat-id"],$con);
}
}
}
}
mysqli_free_result($res_sub);
mysqli_free_result($res);
return $cats;
}