1

I'm trying to generate a JSON string that includes the id and url for all my categories, subcategories, and sub-subcategories. The code below only gets me as far as the top-level category, but I also need the second and third as well. My goal is to create a dynamically updating sitemap that decodes the string and makes an unordered list of every category level.

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;
}

I get something like this:

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

But I want something like this:

{
    "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"
            }
    }
}

Appreciate your time and help!

1 Answer 1

3

You can use some functionality provided by Mage_Catalog_Model_Resource_Category_Tree for this. See if this script works for you:

<?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)));
3
  • Thank you so much! I haven't got it working exactly as I need it to yet, but you put me on a path to understanding the way to get there better and I feel close to getting it to work now. I appreciate it!
    – rosacodes
    May 6, 2014 at 13:45
  • Glad I could help! - perhaps you should accept the answer for others who have similar issues, or tell us what else you are missing so we can continue helping you out. May 6, 2014 at 13:49
  • Got it! Sorry, still new to Stack. I'm going to tease out some of these syntax errors and get back here with any questions I still have in a few hours.
    – rosacodes
    May 6, 2014 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.