In my magento, I have the following category tree structure like this (note: only a few categories has been expanded):
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).
app/Mage.php
to get the magento models./src/shell/abstract.php
you must setup some params to get all working fine.