You may pay someone to create your store, or you visit our seminar and become a professional yourself with the silver certification
public static function buildCategoryTree($categories) {
// Create a mapping of categories by their IDs
$categoryMap = [];
foreach ($categories as $category) {
$categoryId = $category->virtuemart_category_id;
$categoryMap[$categoryId] = [
'virtuemart_category_id' => $categoryId,
'category_parent_id' => $category->category_parent_id,
'firstLevelChildren' => [],
'allChildren' => [],
'isLeaf' => true
];
}
// Build the tree structure
foreach ($categoryMap as $categoryId => &$category) {
$parentId = $category['category_parent_id'];
if ($parentId !== 0 && isset($categoryMap[$parentId])) {
$categoryMap[$parentId]['firstLevelChildren'][] = $categoryId;
$categoryMap[$parentId]['isLeaf'] = false;
}
}
// Populate allChildren array recursively
foreach ($categoryMap as $categoryId => &$category) {
$category['allChildren'] = self::getAllChildren($categoryMap, $categoryId);
}
// Return the result as array with virtuemart_category_id as keys
return $categoryMap;
}
private static function getAllChildren(&$categoryMap, $categoryId) {
$children = [];
foreach ($categoryMap as $id => &$category) {
if ($category['category_parent_id'] === $categoryId) {
$children[] = $id;
$children = array_merge($children, self::getAllChildren($categoryMap, $id));
}
}
return $children;
}
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from('#__virtuemart_categories');
$db->setQuery($query);
$categories = $db->loadObjectList();
$categoriesWithChildren = self::buildCategoryTree($categories);
print_r($categoriesWithChildren);
[68] => Array
(
[virtuemart_category_id] => 68
[category_parent_id] => 36
[firstLevelChildren] => Array
(
[0] => 221
[1] => 222
)
[allChildren] => Array
(
[0] => 221
[1] => 222
[2] => 442
[3] => 1109
[4] => 1110
[5] => 1281
[6] => 1299
)
[isLeaf] => false
)
Page created in 0.130 seconds with 12 queries.