php – Assign category related products (Magento 1)

We have a magento store and we have more than 1000 products listed. We want to assign products related to chance, but they must be within the category. For example, if a product appears in the Men >> T-Shirts category, the related products should also belong only to the T-Shirts category. Is there any way to do it using code instead of manually assigning related products?