以下是我的表结构:
菜单表
id title position
--------------------
1 Test home
2 Test2 home
分类
cid name parent parent_menu
--------------------------------
1 ABC 0 1
2 DEF 0 2
3 GHI 1 0
4 JKL 2 0
类别说明
id cat_id catdesc slug
-------------------------------
1 1 ABC_DESC abc
2 2 DEF_DESC def
3 3 GHI_DESC ghi
4 4 JKL_DESC jkl
Menu table
处理菜单标题的位置。Category table
处理类别名称和其他参数。 (如果parent = 0则表示这是主要类别,依此类推..)Category Description table
处理描述,slug和其他参数。现在我想显示如下数据
Name Description Edit Delete /*table headings*/
-------------------------------------------------------
Menu Title: (Test) Main Category Name: (ABC)
------------------------------------------------------
GHI GHI_DESC edit_icon delete_icon
______________________________________________________
Menu Title: (Test2) Main Category Name: (DEF)
------------------------------------------------------
JKL JKL_DESC edit_icon delete_icon
我尝试使用JOINS并在PHP中操作数据,但没有运气。
SELECT * FROM `category` t1 LEFT JOIN `category_description` t2 ON t1.cid = t2.cat_id WHERE 1
然后在PHP中我尝试如下
<?php $i = 1; foreach($subcat as $sub) { ?>
<?php if($sub->parent == 0) { ?>
<tr><td><?php echo $sub->name ?></td></tr>
<?php } ?>
<?php if($sub->parent != 0) { ?>
<tr><td><?php echo $sub->name ?></td><td><?php echo $sub->catdesc ?></td>
<td>Edit</td><td>Delete</td></tr>
<?php } ?>
<?php } ?>
以上打印表格如下:
Main Category Name: ABC
Main Category Name: DEF
------
GHI GHI_DESC
JKl JKL_DESC
请根据需要建议如何打印。
答案 0 :(得分:1)
假设parent_menu来自菜单表中的id,请尝试:
SELECT t1.title, t2.name, t2.parent, t2.parent_menu, t3.catdesc
FROM menu t1
LEFT JOIN category t2 ON t1.id=t2.parent_menu
LEFT JOIN description t3 ON t2.cid=t3.cat_id
GROUP BY t2.name
答案 1 :(得分:0)
你可以使用旧的MySQL方法:
select mt.title, cat.name, cdesc.catdesc from menu_title mt, category cat, category_description cdesc where mt.id = cat.parent_menu and cat.cid = cdesc.cat_id
答案 2 :(得分:0)
我建议您构建一个树,然后借助ArrayIterator和RecursiveIteratorIterator迭代树。
要构建树,您可以调整此代码示例:
$tree = array();
foreach($result_set as $result) {
if ($result["parent"] == 0) {
$tree["cat"][$result["cid"]]["parent"] = $result;
} else {
$tree["cat"][$result["parent"]]["child"][$result["cid"] = $result;
}
}
记住:你必须调整它!
然后你可以像这样实现迭代器:
class CategorieTreeIterator extends ArrayIterator implements RecursiveIterator
{
public function getChildren()
{
$link_data = $this->current();
$cid = key($link_data["cat"]);
return new CategorieTreeIterator($link_data["cat"][$cid]["child"]);
}
public function hasChildren()
{
$link_data = $this->current();
$cid = key($link_data["cat"]);
return !empty($link_data["cat"][$cid]["child"]);
}
}
同样,你必须调整它 要显示数据,您现在可以迭代使用它:
$cat_tree_iter = new CategorieTreeIterator($tree);
$rec_iter_iter = new RecursiveIteratorIterator($cat_tree_iter, RecursiveIteratorIterator::SELF_FIRST);
foreach($rec_iter_iter as $iter) {
//display data with help of $iter->getDepth();
}