简体   繁体   English

Magento-从产品ID获取特定的类别名称

[英]Magento - get specific category name from product id

This is my code: 这是我的代码:

$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if ($category_id == 3 || 4 || 5 || 6 || 7 || 8) {
          echo $_cat->getName();
     }
}

I want to display only one specific category(cat) name: 我只想显示一个特定的类别(猫)名称:

If the product (it is always just one which is displayed) is in a specific cat (the specific cat ids are: 3,4,5,6,7,8) it should display the cat name (but only the cat name of one of these ids). 如果产品(总是只显示一种)位于特定的猫中(特定的猫ID:3、4、5、6、7、8),则应显示猫的名称(但仅显示猫的名称)这些ID之一)。

Every product is in only one of these cats but it has more cats (child cats and default cat). 每个产品仅属于其中的一只猫,但它拥有更多的猫(子猫和默认猫)。

For Example: I have a product from cat 4. My code displays all cat names (default, cat 4 and the child cats), but i just want the name of cat 4. My if expression doesn't work. 例如:我有一个来自cat 4的产品。我的代码显示所有cat名称(默认为cat 4和子cat),但我只想要cat 4的名称。我的if表达式不起作用。 Has anybody an idea how to fix this? 有谁知道如何解决这个问题?

You want to check whether your variable is part of a set, so it is wise to build an array and check whether the value is in the array: 您要检查变量是否是集合的一部分,因此明智的做法是构建一个数组并检查该值是否在数组中:

$elements = array(3, 4, 5, 6, 7, 8);
$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if (in_array($category_id, $elements)) {
          echo $_cat->getName();
     }
}

You can get Magento category name or category id of particular product by product id. 您可以通过产品ID获取Magento类别名称或特定产品的类别ID。 You following code: 您下面的代码:

    $_proId  = $this->getProduct()->getId();
    $product = Mage::getModel('catalog/product')->load($_proId);
    $cats = $product->getCategoryIds();

    foreach ($cats as $category_id) {
        $_cat = Mage::getModel('catalog/category')->load($category_id) ;
        $currentCategory = $_cat->getId();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM