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

Amd 让它返回与键“足球”相关联的数组,我已经尝试了几种方法,每次我出现错误时,也许我错过了一些东西,所以我在这一点上接受一些建议。

4

2 回答 2

3

它不起作用的原因是您正在循环访问 $mappings 数组,并试图查看 $teamType 是否在 $item.xml 中。

你的方法有两个问题:

  1. 您正在 $item(这是数组('nfl', 'college-football'))中查找 'football'。这是不正确的。
  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;
}
于 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 回答