Items in Subcategories

More
11 years 9 months ago #39989 by rubenreyes
Hello

We are updating a template and we would like to display a category items, subcategories and items in the subcategories.

We can see that when we activate in the category options to display subcategory items they all get included in $this->items

So far we have been doing the following: cycle through the subcategories, and then on each subcategory cycle through all the items to see which one is assigned to it, with a code like this:
Code:
foreach ($this->categories as $subcat) { // some code to display subcategory info foreach($this->items as $item) { if($item->catid == $subcat->id) { // some code to display item } } }

My question is: is there a more "elegant" way to do this without the several cycles? Perhaps having a list of items under each category (even if only the item id). We noticed that there is $this->categories[x]->assigneditems but it is always null.

Perhaps we need to do something so that "assigneditems" is populated? This will help not only with having a more efficient code, but will allow us to make decisions that are based on the number of items in the subcategory, specially when there are none.

Thank you

Ruben

Please Log in or Create an account to join the conversation.

More
11 years 9 months ago #39992 by ggppdk
Replied by ggppdk on topic Items in Subcategories
Hello,
about your code it involves (usually small/very arrays)
it is

O(m*n)

(where m is the number of categories and n is the number of items)

the following code is
O(n+n) ==> O(n)
Code:
$cat_item_map = array(); foreach($this->items as $item) { $cat_item_map[$item->catid][] = $item; } foreach ($this->categories as $subcat) { foreach($cat_item_map[$subcat->id] as $item) { //... display item, or do something with it } }

NOTE your original code and this code will skip items that their main category does not belong to the subcategories


-- Flexicontent is Free but involves a big effort on our part.
Like the our support? (for a bug-free FC, despite having a long list of functions) Like the features? Like the ongoing development and future commitment to FLEXIcontent?
-- Add your voice to the FLEXIcontent JED listing with a 5-star...

Please Log in or Create an account to join the conversation.

Moderators: vistamediajoomlacornerggppdk
Time to create page: 0.278 seconds
Cookies user preferences
We use cookies to ensure you to get the best experience on our website. If you decline the use of cookies, this website may not function as expected.
Accept all
Decline all
Essential
These cookies are needed to make the website work correctly. You can not disable them.
Display
Accept
Analytics
Tools used to analyze the data to measure the effectiveness of a website and to understand how it works.
Google Analytics
Accept
Decline
Save