Thursday, 12 September 2013

PHP Category Reverse Traversal Algorithm

PHP Category Reverse Traversal Algorithm

pI'm trying to optimize an e-commerce category system with unlimited
category depth (barring system memory limitations). I retrieve all the
categories at once and order them as a multi-dimensional array that
emroughly/em looks like:/p precode[array] ( [0] ( 'CategoryId' =gt; 1,
'ParentCategoryId' =gt; 0, 'Title' =gt; 'Category A', 'SubCategories' =gt;
[array] ( [0] ( 'CategoryId' =gt; 2, 'ParentCategoryId' =gt; 1, 'Title'
=gt; 'Category B', 'SubCategories' =gt; [array] ( [0] ( 'CategoryId' =gt;
3, 'ParentCategoryId' =gt; 2, 'Title' =gt; 'Category C' ) ) ) ) ) )
/code/pre pEach item in the array is actually an object, but for
simplicity I wrote it out kind of like an array format./p pI'm able to
traverse my tree downwards using this function:/p precode/** * Find Branch
using Recursive search by Object Key * @param String Needle * @param Array
Haystack * @return Array */ public static function findBranchByKey($key,
$needle, $haystack) { foreach ($haystack as $item) { if ( $item-gt;$key ==
$needle || ( is_object($item) amp;amp; $item = self::findBranchByKey($key,
$needle, $item-gt;SubCategories)) ) { return $item; } } return false; }
/code/pre pThis finds the object with a matching key and returns it (which
may contain more subcategories). /p pMy issue is figuring out how to
traverse the other direction. For example, using the data above, let's say
I am displaying Category C and want to create bread crumbs of it's
parents. I can't think of a good way to take my strongtree/strong array,
jump to a specific subcategory, then iterate upwards to get each parent. A
resulting array from something like this could be like this so it's easy
to spit them out as bread crumbs:/p precode array( 'Category A', 'Category
B', 'Category C' ) /code/pre pI could probably do this using SQL in my
database but I'd like to retrieve the tree once, cache it, and perform
traversal on that object whenever I need to rather than making tons of
queries./p pTL;DR; How can I traverse upwards in a multidimensional array
of categories?/p

No comments:

Post a Comment