Finding corresponding category in different subtrees of a category group I'm building a language switcher for a clients website. The website consists of multiple regions which can have multiple locales. As regions aren't supported yet in Craft 2, I've worked my way around that in a variety of ways.

For my products section, I have a category group of product categories. The top level of each tree within that group is the region a product belongs to. So you can have something like this:


US


Category US A


Category US A 1


Europe


Category Europe A


Category Europe A 1




So when selecting category 'US A 1' I know the region this product needs to be shown in is US and I have the correct category too.

Now when switching languages, I check if the region also changes. If so, I have the ID of the new region (which is the first level category of a tree within that group). So, I check if this entry exists related to that category ID. 
If so I need to find the exact same subcategory in the Europe tree as was selected in the US tree (so find 'Europe A 1') and check if the entry is also related to that category. If so, send the user to that URL. Problem is I don't know how to do that last step as all I'm getting is an array of categories without any hierachy.

Important: I need this in a plugin in PhP so no Twig.

UPDATE

The only link between for example: 'US A 1' and 'Europe A 1' will be the slug. I'll have to enforce the client to make sure similar categories share the same slug. (Thanks to carlcs to ask this important info I forgot to mention :)
I would just split that category group, if possible, and offer one group for the region and one for the “A1” type of categories.

If this is out of question, you need to find a way to link your categories. Give them the same slug or use another field to make the connection (e.g. a Categories field) and use the corresponding criteria param to filter for the entry in the new locale.

$currentLocaleCategory = $entry-&gt;myCategoriesField-&gt;last();

if ($currentLocaleCategory) {
    $criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
    $criteria-&gt;locale = $locale;
    $criteria-&gt;descendantOf = $descendantOfParam;
    $criteria-&gt;slug = $currentLocaleCategory-&gt;slug;

    $newLocaleCategory = $criteria-&gt;first();
}