Magento 1.9 Category – Get Category Tree as an Assoc Array

categorycategory-treemagento-1.9

In my magento, I have the following category tree structure like this (note: only a few categories has been expanded):

enter image description here

I would like to generate an array that looks like this:

$categories = [
    'Default Category' => [
        'HAIR' => [
            'Hair Colouring' => [
                'Permanent Hair Colour',
                // ...etc
            ],
            'Styling' => [
                'Gel / Wax / Paste / Po',
                // ...etc
            ]
        ],
        // ... etc
    ]
];

Is this possible? It would be a bonus if I can get the product count in each category node; just like in magento admin backend; for example: Hair colouring (1840)

I have been searching online and I found this code (my starting point):

http://magentotutorial.in/how-to-create-categories-tree-structure-in-magento-programmatically/

But it doesn't quite work, this is what I get back: <ul></ul>


Update

After doing some further searching, I had some luck loading the category tree data (linearly) like this:

<?php

require_once 'app/Mage.php';
$app = Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$categoriesArray = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->load()
        ->toArray();
$categories = array();
foreach ($categoriesArray as $categoryId => $category) {
    if (isset($category['name']) && isset($category['level'])) {
        $categories[] = array(
            'level'  => $category['level'],
            'label' => $category['name']
        );
    }
}

print_r($categories);

This produces the following output:

Array
(
    [0] => Array
        (
            [level] => 0
            [label] => Root Catalog
        )
    [1] => Array
        (
            [level] => 1
            [label] => Default Category
        )
    [2] => Array
        (
            [level] => 2
            [label] => HAIR
        )
    [3] => Array
        (
            [level] => 3
            [label] => Hair Colouring
        )
    [4] => Array
        (
            [level] => 4
            [label] => Permanent Hair Colour
        )
// etc...

I am just now trying to figure out how to parse this output in the structure I want (as shown above).

Best Answer

Ok, based on your Updated Question:

  • You can iterate the collection without use ->toArray() method
  • If you want to exclude the root categories add ->addAttributeToFilter('level', array('gt' => 2))

Then you can use path to sort and create the tree, you can achieve this in many ways iterating the collection and exploding the path. Ordering categories by path you will ensure create first the parents and then the childs, don't forget to use the category_id as key in the array

Alternatively you can use the built-in tree:

Mage_Catalog_Helper_Category::getStoreCategories(...)

that retrieves a

Varien_Data_Tree_Node_Collection

But you can't export it to array directly, you must itarate it and get the childs recursively for each node to get a nested array.

Related Topic