好的,尝试创建一个我可以传递变量的函数,它将搜索一个静态的当前硬编码多维数组中的键,并返回与找到的键匹配的数组(如果找到)。
这就是我到目前为止所做的。
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让它返回与关键“足球”相关联的阵列,我已经尝试了几种方式,每次我都错了,也许我错过了一些东西,所以我现在就提出一些建议。< / p>
答案 0 :(得分:3)
它不起作用的原因是你循环遍历$ mappings数组,并试图查看$ teamType是否在$ item中。
您的方法存在两个问题:
我个人的偏好是使用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;
}
答案 1 :(得分: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;}
}