1

OK、変数を渡すことができる関数を作成しようとしています。これは、現在ハードコードされている静的な多次元配列のキーを検索し、見つかったキーに一致する配列を返します (見つかった場合)。

これは私がこれまでに持っているものです。

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");

キー「サッカー」に関連付けられた配列を返す必要があります。これをいくつかの方法で試しましたが、偽になるたびに、何かが欠けている可能性があるので、この時点でアドバイスを受けてください。

4

2 に答える 2

3

それが機能しない理由は、$ mappings配列をループしていて、$teamTypeが$itemにあるかどうかを確認しようとしているためです。

あなたのアプローチには2つの問題があります:

  1. $ item(これはarray('nfl'、'college-football'))で'football'を探しています。これは正しくありません。
  2. 使用した「キー」ではなく、「値」が配列にあるかどうかをチェックするin_array()を使用しています。array_key_exists()関数を確認することをお勧めします-これがあなたが使用するつもりだったものだと思います。

私の個人的な好みは、array_key_exists()の代わりにisset()を使用することです。構文は少し異なりますが、どちらも同じ仕事をします。

改訂されたソリューションについては、以下を参照してください。

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;
}
于 2012-11-21T06:27:51.150 に答える
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;}
}
于 2012-11-21T06:48:58.323 に答える