我们的结构与您在下面的屏幕截图中看到的方式类似:
https://github.com/petabridge/akkadotnet-code-samples]
我们的数据库结构如下所示:
这里的数据库表“PID”是父ID,其中0 =父ID。休息PID是同一个id的父ID。
现在我们试图获得“Brand”或“Footware”的所有子类别,因此它应该显示该树下的所有子类别和子子类别细节。这可以通过PHP完成吗?任何循环或任何方式?
谢谢!
答案 0 :(得分:1)
试试这个
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER BY id ASC";
$result=$con->query($sql);
if (mysqli_num_rows($result) > 0)
{
$user_tree_array[] = "<ul>";
while ($row =$result->fetch_object())
{
$user_tree_array[] = "<li>". $row->name."</li>";
$user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
}
$user_tree_array[] = "</ul><br/>";
}
return $user_tree_array;
}
这里的呼叫功能
$res = fetchCategoryTreeList();
foreach ($res as $r)
{
echo $r;
}
答案 1 :(得分:0)
试试这样:
<?php
//connect to mysql and select db
$conn = mysqli_connect('localhost', 'rootuser', 'rootpwd','dbname');
if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));
//call the recursive function to print category listing
category_tree(0);
//Recursive php function
function category_tree($catid){
global $conn;
$sql = "select * from category where pid ='".$catid."'";
$result = $conn->query($sql);
while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' . $row->category;
category_tree($row->id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
endwhile;
}
//close the connection
mysqli_close($conn);
?>
希望这会有所帮助。
答案 2 :(得分:0)
我在我的项目中使用了这个函数,它是一个递归函数。
/ ****获取所有类别功能******* /
function categoryChild($id, $spacing = '') {
$s = "SELECT * FROM category WHERE parent_cat_id = $id ";
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_array($r)) {
$children[$row['category_id']]['category_name'] = $spacing.$row['category_name'];
$children[$row['category_id']]['id'] = $row['category_id'];
$children[$row['category_id']]['child'] = categoryChild($row['category_id'], $spacing . ' ');
}
}
return $children;
}
> /************ GET ALL CATEGORIES FUNCTION****************/
$allcategory = categoryChild(0);
print_r($allcategory);