@@ -130,23 +130,23 @@ public function getCategoryTree(array $categories, int $parentId = 0, array &$vi
130130 $ categoryId = (int ) $ category ['category_id ' ];
131131 $ categoryParentId = (int ) $ category ['parent_id ' ];
132132
133- // First check if this category belongs at this level (parent_id matches)
134- if ($ categoryParentId !== $ parentId ) {
133+ // Skip if category is its own parent or creates a cycle
134+ if ($ categoryId === $ categoryParentId ) {
135135 continue ;
136136 }
137137
138- // Then prevent infinite recursion by checking if we've already processed this category
139- // This check must come after the parent_id check to ensure we only mark categories
140- // as visited when they're actually being added to the tree at the correct level
141- if (isset ($ visited [$ categoryId ])) {
142- continue ;
143- }
138+ if ($ categoryParentId === $ parentId ) {
139+ // Check if this category has already been visited to prevent cycles
140+ if (isset ($ visited [$ categoryId ])) {
141+ continue ;
142+ }
144143
145- // Mark this category as visited
146- $ visited [$ categoryId ] = true ;
144+ // Add the current category to a visited list
145+ $ visited [$ categoryId ] = true ;
147146
148- $ childCategories = $ this ->getCategoryTree ($ categories , $ categoryId , $ visited );
149- $ result [$ categoryId ] = $ childCategories ;
147+ $ childCategories = $ this ->getCategoryTree ($ categories , $ categoryId , $ visited );
148+ $ result [$ categoryId ] = $ childCategories ;
149+ }
150150 }
151151
152152 return $ result ;
0 commit comments