Magento 如果属性值为 x 或 y,则显示自定义块

问题描述 投票:0回答:2

在 view.phtml 上,如果属性平台的值是“xbox”、“playstation”或“nintendo”,我试图获取要显示的自定义块“console”。

我得到了适用于 xbox 的代码,但我该如何解决它,以便该块显示其值而不是 PlayStation 或 nintendo?

兄弟, 托比亚斯

<?php if ($_product->getAttributeText('platform') == "xbox"): ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml() ?><?php endif; ?>
php if-statement magento attributes intersection
2个回答
1
投票

您的意思是您想要为任何控制台使用相同的块吗?我建议使用 switch 语句

将您编写的 if 语句替换为:

switch($_product->getAttributeText('platform')){
  case "xbox" :
  case "nintendo" :
  case "playstation" :
    echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
    break;
  default :
    //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
}

现在您可以通过添加更多

case "other console" :
语句来添加更多控制台。

还有其他方法。您可以从属性值创建所有控制台的数组,然后使用 inArray(); - 如果您的客户端通过 Magento 管理向属性添加更多控制台,这对于一般情况可能会更好。

**编辑**遵循下面的评论

如果属性“platform”是多选的,那么如果选择了一项,则

$_product->getAttributeText('platform')
将是字符串,但如果选择了多个项目,则它将是一个数组。因此,您需要处理一个可以是字符串或数组的变量。这里我们将字符串转换为数组并使用 PHP 方便的 array_intersect() 函数

我建议:

$platformSelection = $_product->getAttributeText('platform');
if (is_string($platformSelection))
{
    //make it an array
    $platformSelection = array($platformSelection); //type casting of a sort
}

//$platformSelection is now an array so:

//somehow know what the names of the consoles are:
$consoles = array('xbox','nintendo','playstation');

if(array_intersect($consoles,$platformSelection)===array())
{
    //then there are no consoles selected
    //here you can put a default other block or show nothing or whatever you want to do if the product is not a console
}
else
{
    //there are consoles selected
    echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml();
}

请注意,array_intersect() 函数严格比较数组元素,即

===
,因此它区分大小写,如果没有交集,该函数将返回一个空数组
array()


0
投票

如果您想要这 3 个值中的任何一个使用相同的块,则应该这样做:

<?php 
$productAttribute = $_product->getAttributeText('platform');
if ($productAttribute == "xbox" || $productAttribute == "playstation" || $productAttribute == "nintendo"): ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('console')->toHtml() ?><?php endif; ?>

如果您想要根据值使用不同的块,则应该这样做:

<?php
$productAttribute = $_product->getAttributeText('platform');
switch ($productAttribute){
  case "xbox":
echo $this->getLayout()->createBlock('cms/block')->setBlockId('xbox')->toHtml();
break;
  case "playstation":
echo $this->getLayout()->createBlock('cms/block')->setBlockId('playstation')->toHtml();
break;
  case "nintendo":
echo $this->getLayout()->createBlock('cms/block')->setBlockId('nintendo')->toHtml();
break;
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.