I want to show the entries which have same category of that entry. The entry might have multiple categories, so I want to merge the result. If there is a result, then only the whole structure will be shown. The title 'Recommended Product' should only show one time. Currently, the issue is if there are three categories, the whole structure will show three times.
{% set subcategories = craft.categories.group('prodCat').descendantOf(prodCat).level(2).relatedto(entry) %}
{% if subcategories | length %}
{% for subcategory in subcategories %}
{% set relatedentry = craft.entries.section('products').relatedTo(subcategories).id('not '~entry.id).all() %}
{% set relatedentry_count = relatedentry|length %}
{% if relatedentry_count > 0 %}
<div>
<h4>Recommended Product</h4>
<ul>
{% for entry in relatedentry %}
<li>{{entry.title}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endfor %}
{% endif %}
Update based on the answer:
I manage to solve the issue after making some tweak of the answer given, just merge the subcategory.
{% set subcategory = craft.categories.group('prodCat').level(2).relatedto(entry) %}
{% set subcategories = subcategory|merge(subcategory) %}
{% if subcategories | length %}
{% set relatedentry = craft.entries.section('products').relatedTo(subcategories).id('not '~entry.id).all() %}
{% set relatedentry_count = relatedentry|length %}
{% if relatedentry_count > 0 %}
<div>
<h4>Recommended Product</h4>
<ul>
{% for entry in relatedentry %}
<li>{{entry.title}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% endif %}