2012-11-21 27 views
1

好吧,試圖做一個函數,我可以傳遞一個變量,它將搜索靜態當前硬編碼的多維數組中的鍵,並返回匹配到找到的鍵的數組如果找到)。陣列映射函數,每次返回false

這是我到目前爲止。

public function teamTypeMapping($teamType) 
{ 
    //we send the keyword football, baseball, other, then we return the array associated with it. 
    //eg: we send football to this function, it returns an array with nfl, college-football 
    $mappings = array(
       "football" => array('nfl', 'college-football'), 
       "baseball" => array('mlb', 'college-baseball'), 
       "basketball" => array('nba', 'college-basketball'), 
       "hockey" => array('nhl', 'college-hockey'), 
       ); 
    foreach($mappings as $mapped => $item) 
    { 
     if(in_array($teamType, $item)){return $mapped;} 
    } 
    return false; 
} 

而且我想打個電話吧,例如:

teamTypeMapping("football"); 

AMD都將其返回與關鍵字「足球」相關的陣列,我已經試過這幾種方法,每次我冒出虛假的,也許我錯過了一些東西,所以我現在就採取一些建議。

+0

ü可以用這個也如果($ teamType == $映射){$返回映射;}做 – Dikku

+0

這個'的foreach取代你的foreach( $映射爲$映射=> $項目) { \t \t如果($映射== $ teamType){ \t \t \t返回$映射[$映射]; \t \t} }' –

+0

或者回答@Luke Mills給出的答案 –

回答

3

它不起作用的原因是您正在循環$ mappings數組,並試圖查看$ teamType是否在$ item中。

有兩個問題你的方法:

  1. 您正在尋找在$項目(這是數組(「橄欖球」,「大學生足球」))爲「足球」。這是不正確的。
  2. 您正在使用in_array(),它檢查數組中是否存在「值」,而不是您使用的「鍵」。你可能想看看array_key_exists()函數 - 我認爲這是你的意思。

我個人偏好使用isset()而不是array_key_exists()。語法略有不同,但都做同樣的工作。

請參閱以下修訂的解決方案:

public function teamTypeMapping($teamType) 
{ 
    //we send the keyword football, baseball, other, then we return the array associated with it. 
    //eg: we send football to this function, it returns an array with nfl, college-football 
    $mappings = array(
       "football" => array('nfl', 'college-football'), 
       "baseball" => array('mlb', 'college-baseball'), 
       "basketball" => array('nba', 'college-basketball'), 
       "hockey" => array('nhl', 'college-hockey'), 
       ); 
    if (isset($mappings[$teamType])) 
    { 
     return $mappings[$teamType]; 
    } 
    return false; 
} 
+0

那麼,做了這份工作,謝謝。同時感謝您打破我的方法中的缺陷。不是經常獲得高質量的答案,它很好地知道我錯在哪裏。 – chris

1

我檢查你函數

public function teamTypeMapping($teamType) 
{ 
    //we send the keyword football, baseball, other, then we return the array associated with it. 
    //eg: we send football to this function, it returns an array with nfl, college-football 
    $mappings = array(
       "football" => array('nfl', 'college-football'), 
       "baseball" => array('mlb', 'college-baseball'), 
       "basketball" => array('nba', 'college-basketball'), 
       "hockey" => array('nhl', 'college-hockey'), 
       ); 
    foreach($mappings as $mapped => $item) 
    { 
     if(in_array($teamType, $item)){return $mapped;} 
    } 
    return false; 
} 

而當你想使對它的調用,例如:

teamTypeMapping("football"); 

然後它返回false。

解決方案是如果希望數組,那麼你想

foreach($mappings as $mapped => $item) 
{ 
    if($mapped == $teamType){return $mapped;} 
}