在Magento单一产品视图页面中,我使用foreach循环显示具有echo()
函数的当前产品类别的名称
<?php $categories = $_product->getCategoryIds(); ?>
<?php foreach($categories as $k => $_category_id): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
<a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
<?php endforeach; ?>
但是,当产品分配到多个类别时,结果为类别名称类别名称类别名称,格式不正确。有没有办法在每个类别之后添加逗号(例如:类别名称,类别名称,类别名称),除了最后一个类别可能是使用implode()函数?
答案 0 :(得分:0)
试试这个。没有内爆。只需检查您是否已打印第一类。如果是,则在每个其他类别之前添加逗号。
<?php $categories = $_product->getCategoryIds(); ?>
<?php $firstSet = false;?>
<?php foreach($categories as $k => $_category_id): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
<?php if ($firstSet):?>, <?php endif;?><a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
<?php $firstSet = true;?>
<?php endforeach; ?>
答案 1 :(得分:0)
这非常简单。由于您要获得类别名称,请尝试以下:
<?php echo $_category->getName().", "; ?>
答案 2 :(得分:0)
<?php $categories = $_product->getCategoryIds(); ?>
<?php foreach($categories as $k => $_category_id): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
<a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName()."," ?>
</a>
<?php endforeach; ?>
Note : concatenate , using .
答案 3 :(得分:0)
<?php
$categories = $_product->getCategoryIds();
foreach($categories as $k => $_category_id){
$_category = Mage::getModel('catalog/category')->load($_category_id);
$category_str = '<a href="' . $_category->getUrl() . '">' . $_category->getName() . '</a>, ';
}
?>
<?php echo trim($category_str, ', ') ?>