Page 1 of 1

Array / Object needed with the full category_path

Posted: Wed Sep 22, 2021 2:44 pm
by loop
Hi all
I'm on a modification of the Adverts.php class and i need a way (which is not producing heavy load on a sql search) to see if a parent of a specific category is a main category...

i want to have specific ads show only in every category under the maincategory 2 for example

example:
Homeelectronics (cat_id:2)-> TV (cat_id:8)-> LED TV(cat_id:12)
i need to know if "12" is in maincategory "2"

so the question is, is there a variable, whenn i have the category_id 12, to know the full path of it (2_8_12) so i could lookup in the path and look if the first, maincategory is a "2"

thank you in advance!

Re: Array / Object needed with the full category_path

Posted: Wed Sep 22, 2021 6:12 pm
by ecartz

Code: Select all

$category_id = 12;
$ancestors = $GLOBALS['category_tree']->get_ancestors($category_id);
$main_category_id = (count($ancestors) > 0) ? $ancestors[count($ancestors) - 1] : $category_id;
In your example, $main_category_id would be 2.

You could also use find_path to do this, but it would do more work to get the same result.

Re: Array / Object needed with the full category_path

Posted: Thu Sep 23, 2021 5:14 am
by loop
hi ecartz

Thank you so much!
as i would call this code on every categorypage a multipe times (depends how much ads i have) does this code

Code: Select all

$category_id = 12;
$ancestors = $GLOBALS['category_tree']->get_ancestors($category_id);
$main_category_id = (count($ancestors) > 0) ? $ancestors[count($ancestors) - 1] : $category_id;
doesn't make alot querys or no DB querys at all?

Re: Array / Object needed with the full category_path

Posted: Thu Sep 23, 2021 5:47 am
by ecartz
That code makes no DB queries. The query is made to create the category_tree in the first place. That code just uses the resulting data structure.

Re: Array / Object needed with the full category_path

Posted: Thu Sep 30, 2021 8:47 am
by ecartz
ecartz wrote: Wed Sep 22, 2021 6:12 pm You could also use find_path to do this, but it would do more work to get the same result.
Note that when I say that it would do more work, I mean that find_path first generates the cPath from get_ancestors. Then you would have to extract the category ID from the resulting string. Meanwhile, if you use get_ancestors directly, you don't have to create the string, nor do you have to parse anything. The root category ID will always be the last one unless you are in the root category ID, which has no ancestors.

This would be different if you needed the cPath for something. The find_path is a perfectly legitimate way to generate a cPath -- that's why it's there. Like all category_tree calls, it will only do one DB query per page (to populate the tree). Once the tree is built, it refers only to the tree structure stored in memory.