2017-06-28 57 views
-1

爲什麼foreach語句中的if語句不起作用?我的array_search函數也不起作用,即時通訊使用yii框架我不能在Foreach語句中使用If語句

if語句應打印品牌名稱,但它打印假,我可能知道情況爲什麼if語句返回給我一個空值或空,謝謝你推進

function getColumnKey($brand_name){ 
    $columnKey = ''; 

     $five_up_brands = array('K'=>"Coke",'L'=>"Sprite",'M'=>"Royal"); 
     array_search($brand_name, $five_up_brands); 

     foreach ($five_up_brands as $k => $v) { 

      if($v == $brand_name){ 

       $columnKey = $k; 
      } 
     } 

    return $columnKey; 
} 
+2

你能否解釋一下關於 「不工作」?你有錯誤嗎?錯誤的結果? – Mureinik

+2

爲什麼不'返回array_search($ brand_name,$ five_up_brands);' –

+0

我不明白你如何使用'yii'框架與你的問題有關。 – paul

回答

1

我想你想在匹配名牌立即返回,而不是讓循環進入下一個迭代時,條件將不再成立。

function getColumnKey($brand_name){ 
    $columnKey = ''; 

    $five_up_brands = array('K'=>"Coke", 'L'=>"Sprite", 'M'=>"Royal"); 
    /* what is the point of this - it is not used? */ 
    #array_search($brand_name, $five_up_brands); 

    foreach($five_up_brands as $k => $v) { 
     if($v == $brand_name){ 
      return $k; 
     } 
    } 

    return false; 
} 
+0

這應該不重要,你只是得到最後匹配的值而不是第一個(在這種情況下是相同的)。 – jeroen

0

我只是想這個代碼..

它工作正常。它給了我輸出這樣

串(1) 「L」

<?php 
    function getColumnKey($brand_name){ 
     $five_up_brands = array('K'=>"Coke",'L'=>"Sprite",'M'=>"Royal"); 
     return array_search($brand_name, $five_up_brands); 
} 
var_dump(getColumnKey('Sprite')); 
0

陣列搜索將正常工作

$five_up_brands = array('K'=>"Coke",'L'=>"Sprite",'M'=>"Royal"); 
$b = array_search("Coke",$five_up_brands); 
echo "$b"; 

這爲我工作,檢查出來。

希望這有助於

-2

試試這個...工作代碼:

function getColumnKey($brand_name){ 

     $five_up_brands = array('K'=>"Coke",'L'=>"Sprite",'M'=>"Royal"); 

     foreach ($five_up_brands as $k => $v) { 

      if($v == $brand_name){ 

       return $k; 
      } 
     } 

    return false; 
}` 
+0

完全相同的代碼 - 一個解釋 - 已經發布超過7分鐘前... – jeroen