从PHP生成Magento类别和子类别的JSON字符串

时间:2014-05-05 20:20:25

标签: php json magento

我正在尝试生成一个JSON字符串,其中包含我所有类别,子类别和子子类别的id和url。下面的代码只能让我达到顶级类别,但我也需要第二个和第三个类别。我的目标是创建一个动态更新的站点地图,该站点地图解码字符串并生成每个类别级别的无序列表。

public function createCategoryTree() {
$_categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*')->addIsActiveFilter()->addLevelFilter(2)->addOrderField('position'); // load all categories
$arr = array();
if ($_categories){ // if there are categories
  foreach ($_categories as $cat){
    $cat_name = $cat->getName(); // name as key
    if (strlen(stristr($cat_name,'default')) < 3) {
      $cat_id = $cat->getId(); // id
      $cat_url = $cat->getUrl(); // url
      $arr[$cat_id] = array('title'=>$cat_name,'url'=>$cat_url); 
    }
  }
}
print_r (json_encode($arr));
die;
}

我得到这样的东西:

{
    "637": {
        "title": "bikes",
        "url": "http:www.123.com/shop/bicycles "
    }
}

但我想要这样的事情:

{
    "637": {
        "title": "bikes",
        "url": "http:www.123.com/shop/bicycles",
        "children": {
            "658": {
                "title":"wheels",
                "url":"http:www.123.com/shop/bicycles/wheels"
            },
            "489": {
                "title": "pumps",
                "url":"http:www.123.com/shop/bicycles/pumps"
            }
    }
}

感谢您的时间和帮助!

1 个答案:

答案 0 :(得分:3)

您可以使用Mage_Catalog_Model_Resource_Category_Tree提供的一些功能。看看这个脚本是否适合你:

<?php
require_once('../app/Mage.php');
Mage::app();

function getCategoryTree($recursionLevel, $storeId = 1)
{
    $parent = Mage::app()->getStore()->getRootCategoryId();    
    $tree = Mage::getResourceModel('catalog/category_tree');
    /* @var $tree Mage_Catalog_Model_Resource_Category_Tree */

    $nodes = $tree->loadNode($parent)
        ->loadChildren($recursionLevel)
        ->getChildren();
    $tree->addCollectionData(null, false, $parent);

    $categoryTreeData = array();
    foreach ($nodes as $node) {
        $categoryTreeData[$node->getData('entity_id')] = getNodeChildrenData($node);
    }

    return $categoryTreeData;
}

function getNodeChildrenData(Varien_Data_Tree_Node $node)
{
    $data = array(
        'title' => $node->getData('name'),
        'url'   => $node->getData('url_key'),
    );

    foreach ($node->getChildren() as $childNode) {
        if (!array_key_exists('children', $data)) {
            $data['children'] = array();
        }

        $data['children'][$childNode->getData('entity_id')] = getNodeChildrenData($childNode);
    }
    return $data;
}

print_r(json_encode(getCategoryTree(3)));