使用TreeNode方式输出指定查询条件的分类

本文介绍了一种使用Magento框架更高效地获取产品分类的方法。通过利用树形结构模型,该方法可以减少手工构造SQL查询的需求,简化了代码并提高了查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Category Collection手工构造sql输出制定查询条件的分类,效率低,代码复杂,本例介绍另一种方式
<?php
// initialize magento environment for 'default' store
require_once '../../app/Mage.php';
Mage::app('default');

function getStoreCategories($sorted=false, $asCollection=false, $toLoad=true) {
$parent = 6; // 6 是名字为'品牌'的类别id.
$category = Mage::getModel('catalog/category');
if (!$category->checkId($parent)) {
if ($asCollection) {
return new Varien_Data_Collection();
}
return array();
}

$recursionLevel = max(0, 0);

$tree = $category->getTreeModel();
$nodes = $tree->loadNode($parent)
->loadChildren($recursionLevel)
->getChildren();

$tree->addCollectionData(null, $sorted, $parent, $toLoad, true);

if ($asCollection) {
return $tree->getCollection();
} else {
return $nodes;
}
}

function getCategory($categoryNode){
$category = Mage::getModel('catalog/category');
$category->setData($categoryNode->getData());
return $category;
}
/*
* Main Funtion
*/
header("content-Type: text/html ; charset=utf-8");
?>
<!-- 输出两层Category -->
<?php foreach (getStoreCategories() as $_categoryNode) { ?>
<div class="catwrapper2">
<div class="subcat2" id="subcat1">
<?php $category =getCategory($_categoryNode); ?>
<h2 class="maincat inline" id="cat1">
<a href="<?php echo $category->getUrl(); ?>"><?php echo $category->getName(); ?>(<?php echo $category->getProductCount(); ?>)</a>
</h2>
<?php $hasChildren = $_categoryNode->hasChildren(); ?>
<?php if($hasChildren){
foreach ($_categoryNode->getChildren() as $subCategoryNode){
$subCategory =getCategory($subCategoryNode);
?>
<a href="<?php echo $subCategory->getUrl(); ?>"><?php echo $subCategory->getName(); ?></a>
<?php
}
}
?>
</div>
</div>
<?php } ?>


代码范例中的getCategory方法是获得Node对应的Cateogry模型实例,目的仅仅是为了调用它的getUrl方法.

下面是我机器上的输出结果:
[img]http://dl.iteye.com/upload/attachment/467070/266a8a60-2a82-3855-ac14-eb985c864133.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值