<?php
class Bruce_Account_categoriesController extends Mage_Core_Controller_Front_Action {
public function nodeToArray(Varien_Data_Tree_Node $node) {
$result = array ();
$result ['category_id'] = $node->getId ();
$result ['parent_id'] = $node->getParentId ();
$result ['name'] = $node->getName ();
$result ['is_active'] = $node->getIsActive ();
$result ['position'] = $node->getPosition ();
$result ['level'] = $node->getLevel ();
$result ['children'] = array ();
foreach ( $node->getChildren () as $child ) {
$result ['children'] [] = $this->nodeToArray ( $child );
}
return $result;
}
public function load_tree() {
$tree = Mage::getResourceSingleton ( 'catalog/category_tree' )->load ();
$store = 1;
$parentId = 1;
$tree = Mage::getResourceSingleton ( 'catalog/category_tree' )->load ();
$root = $tree->getNodeById ( $parentId );
if ($root && $root->getId () == 1) {
$root->setName ( Mage::helper ( 'catalog' )->__ ( 'Root' ) );
}
$collection = Mage::getModel('catalog/category')->getCollection()
->setStoreId($store)
->addAttributeToSelect('name')
//->addAttributeToSelect('id')
->addAttributeToSelect('is_active');
$tree->addCollectionData ( $collection, true );
return $this->nodeToArray ($root );
}
public function print_tree($tree, $level) {
$level ++;
foreach ( $tree as $item ) {
echo str_repeat ( "*", $level ) . $item ['name'] . '*' . $item ['category_id'] . "<br>";
$this->print_tree ( $item ['children'], $level );
}
}
public function listallCategoriesAction() {
$tree = $this->load_tree();
$jsonresult = json_encode ( $tree );
echo $jsonresult;
// $this->print_tree ( $tree ['children'], 0 );
}
}
?>
2. 在Magento中获取指定分类下的产品。
01
02
03
04
05
|
$products
= Mage::getModel(
'catalog/category'
)->load(
$category_id
)
->getProductCollection()
->addAttributeToSelect(
'*'
)
->addAttributeToFilter(
'status'
, 1)
->addAttributeToFilter(
'visibility'
, 4);
|
将上面的$category_id修改为需要显示产品的分类id,该id可以在分类页面中看到。上述代码中还捎带了一些过滤,产品状态为激活,并处于可见状态。