2012-01-19 29 views
0

我有以下代碼:PHP添加圖片到標題,如果某個詞是用來

<h2> 
    <?php echo $this->item->title; ?> 
</h2> 

取決於字拉進標題,我需要一個不同的圖像放置在標題的左邊文本。

圖片:uk.png,france.png,germany.png

因此,如果標題文本說法國,我需要的france.png圖像中拉。所以我需要一個可以使用的圖像和標題列表,如果標題與圖像不匹配,則不顯示圖像。

希望這是有道理...

+0

PHP的數組*尤其是*非常適合於映射「鑰匙」到「值」。這是否給你一個提示? – Jon

+0

你不能使用SWITCH case語句來實現這個嗎? –

回答

1
<?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> 
+0

沒有任何造型,這會將圖像放在標題上方(OP要求「向左」)。只是挑剔:) – zrvan

0

例如:

function getPic($title) 
{ 
    static $pics = array('uk'  => 'uk.png', 
         'france' => 'france.png', 
         'germany' => 'germany.png'); 
    return isset($pics[$title]) ? "<img src='{$pics[$title]}' >" : ""; 
} 
0

你可以寫一個函數返回的圖像文件,根據所輸入的字符串,根據你的榜樣,我們假設是$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);?>" /> 

有一個偉大的日子。

+0

首先,正確的關鍵字是「foreach」,而不是「每個」。其次,爲什麼你需要在那裏循環?爲什麼不檢查數組中是否存在某個鍵,並且在這種情況下只返回'$ images [$ input]'? –

0

這可能不是您的問題的正確答案,但對於鏈接,您可以使用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-kreation

只要我想添加這個,因爲這是一個很好的提示,任何人想要添加圖標鏈接取決於鏈接的部分,這有點類似於你想要的。

0

使用國名作爲顯示相應圖像的關鍵可能被認爲不是非常可靠的解決方案。

我建議使用ISO 3166-1國家代碼作爲鍵。然後,根據國家代碼,你可能有兩個函數返回國家名稱和圖像。

你可能會高達成才一樣,(我沒有使用類和錯誤在這個例子中處理故意):

<?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>