这是我的代码:
$convertTitle = $this->art->catList(); // gets an array which has other arrays as its values
foreach($convertTitle as $cT){ // cycle through the smaller arrays
if(in_array($cat, $cT)){ // if "xx" is found in a smaller array
$data['title'] = $cT['full']; // set the $title to the full form corresponding to the abbreviated xx ($cat)
}
if(!in_array($cat, $cT)){
$data['title'] = "Sorry, an error occurred."; // if it's not found, choose an alternate title
$data['error'] = 1; // throw the error
}
}
为了调试,我一直在打印in_array($cat, $cT)
,当我期望它时,它输出1.当我期望它时,它也输出0。所以它似乎在起作用。我甚至可以print($data['title']);
并显示正确的标题!但无论in_array()
是输出1还是0,我的第二个if语句总是覆盖第一个,而I $错误总是出现1.什么给出?
我尝试过的一些解决方案:
if(!in_array($cat, $cT)...
if(in_array($cat, $cT) == false/0/null)...
else...
我真的不知道为什么当我想要的时候标题 位于变量中时它没有输出正确的标题!
编辑:
这是print_r($convertTitle);
Array ( [0] => Array ( [handle] => dr [full] => Drawings ) [1] => Array ( [handle] => f [full] => Films & Stills ) [2] => Array ( [handle] => pa [full] => Paintings ) [3] => Array ( [handle] => ph [full] => Photography ) [4] => Array ( [handle] => po [full] => Portraits ) )
答案 0 :(得分:3)
为什么不只是else
?
if (in_array()) {
...
} else {
...
}
当条件是彼此的布尔对立时,有两个单独的if()测试基本没有意义。
另外,请记住,您的foreach()
会迭代许多项目。对于数组中没有的 EVERY 项,您将$error
设置为TRUE。但是当你做匹配时,你不会将其重置为FALSE。所以
array item #1 -> not found, so error => true
array item #2 -> not found, so error => true
array item #3 -> found! -> don't change error, it's still true
array item ....
etc...
答案 1 :(得分:0)
您在foreach
循环的每次迭代中都会覆盖您的值,因此最终会得到title
的最后一个值的结果,并且您的error
将保留一次它已经确定。
除此之外,你应该写一下:
if (in_array()) {
} else {
}
答案 2 :(得分:0)
感谢您的回答!我忘记了即使在找到正确的条目后,循环也会反复运行。为了将来参考,以下是有效的代码:
$convertTitle = $this->art->catList();
foreach($convertTitle as $cT){
if(in_array($cat, $cT)){
$data['title'] = $cT['full'];
$data['error'] = 0;
break;
}
else{
$data['title'] = "Sorry, an error occurred.";
$data['error'] = 1;
}
}