magento 2 categories code example
Example: magento 2 get all categories in array
create this file inside magento_project pub/category_tree.php
<?php
set_time_limit(0);
ini_set('display_errors', 1);
ini_set('memory_limit','1024M');
use Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$parentCategoryId = 2;
$category = $objectManager->create('Magento\Catalog\Model\Category')->load($parentCategoryId);
$childCategory['parent']['name'] = $category->getName();
$childCategory['parent']['id'] = $category->getId();
$childCategory['parent']["child"] = getCategory($parentCategoryId);
function getCategory($parentCatId)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryRepository = $objectManager->create('Magento\Catalog\Model\CategoryRepository');
$parentcategories = $categoryRepository->get($parentCatId);
$categories = $parentcategories->getChildrenCategories();
$i=0;
$ChildCategoryValue = [];
foreach($categories as $category){
$ChildCategoryValue[$i] = ['name' => $category->getName(), 'id' => $category->getId()];
$childCat = getCategory($category->getId());
if($childCat){
$ChildCategoryValue[$i]['child'] = $childCat;
}
$i++;
}
return $ChildCategoryValue;
}
echo '<pre>';
print_r($childCategory);
echo '</pre>';