我有以下代码:
<h2>
<?php echo $this->item->title; ?>
</h2>
根据单词作为标题,我需要在标题文本的左侧放置一个不同的图像。
图片:uk.png,france.png,germany.png
因此,如果标题文本显示法国,我需要插入France.png图像。所以我需要一个"可以"使用的图片和标题列表,如果标题与图片不匹配,就不会显示任何图片。
希望这有意义。。。
<?php
$images = array (
'France' => 'france.png',
'UK' => 'uk.png',
'Germany' => 'germany.png'
);
if (isset($images[$this->item->title])) {
?>
<img src="<?php echo $images[$this->item->title]; ?>" />
<?php } ?>
<h2>
<?php echo $this->item->title; ?>
</h2>
例如:
function getPic($title)
{
static $pics = array('uk' => 'uk.png',
'france' => 'france.png',
'germany' => 'germany.png');
return isset($pics[$title]) ? "<img src='{$pics[$title]}' >" : "";
}
您可以编写一个函数,根据输入字符串返回图像文件,根据您的示例,我们假设它是$this->item->title
。它的主要目的是在从输入字符串中确定"country"后返回一个字符串。
function getCountryImage($input)
{
// an array containing the mapping of country names to image file names
$images = array(
'France' => 'france.png',
'UK' => 'uk.png',
'Germany' => 'germany.png' );
for each( $images as $country => $filename )
if( $country == $input )
return $filename;
return '';
}
如果要显示图像,只剩下一件事:
<img src="[image path]/<?php echo getCountryImage($this->item->title);?>" />
祝你今天过得愉快。
这可能不是您问题的正确答案,但对于链接,您可以使用css获得您想要的内容。
a[href$='.zip'], a[href$='.rar'], a[href$='.gzip'] {
background:transparent url(../images/zip.png) center left no-repeat;
display:inline-block;
padding-left:20px;
line-height:18px;
}
有关更多示例,请参阅web kration。
我想添加这个,因为这是一个很好的提示,对于任何想根据链接的部分向链接添加图标的人来说,这与你想要的有点相似。
使用国家名称作为键来显示相应的图像可能被认为不是非常可靠的解决方案。
我建议使用ISO 3166-1国家代码作为密钥。然后,根据coutry代码,您可能有两个函数,返回国家名称和图像。
你可能会遇到这样的情况(我在这个例子中没有故意使用类和错误处理):
<?php
function getCountryNameByIsoCode($iso_code)
{
static $country_names = array ("FRA" => "France", "GBR" => "United Kingdom", ...);
return $country_name[$code];
}
function getCountryFlagImageFileNameByIsoCode($code)
{
static $country_flags = array ("FRA" => "france.png", "GBR" => "uk.png", ...);
return $country_flags[$iso_code];
}
?>
<h2>
<img src="/img/<?php echo getCountryFlagImageFileNameByIsoCode($this->item->iso_code); ?>" alt="" />
<?php echo getCountryNameByIsoCode($this->item->iso_code); ?>
</h2>