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!