2017-10-11 59 views
0

我已经将复选框数据转换为一个字符串存储在我的数据库中。当我搜索in_array时,PHP爆炸函数只允许我检测第一个数组项。为什么?

但是,当我尝试使用爆炸函数将字符串转换回数组时,我无法在in_array中搜索除第一项外的任何内容。为什么?

$rolepref = explode(',', $roles); 
print_r($rolepref) = [0] Strategy [1] Operations 
if (in_array("Strategy", $rolepref) { echo "yes" } => Will echo yes 
if (in_array("Operations", $rolepref) { echo "yes" } => Does not work 

我在这里错过了什么?提前致谢!

+0

你可以发布你想要检查的实际数组吗?和实际的代码。看起来你刚刚输入了它,因为它没有完成(在if语句中缺少右括号)。 –

回答

1

很可能你在爆炸数据后有空白。尝试用装饰

$roles = "Strategy, Operations"; 
$rolepref = array_map('trim', explode(',', $roles)); //trim and explode data 
if (in_array("Strategy", $rolepref)) { echo "yes"; } 
if (in_array("Operations", $rolepref)) { echo "yes"; } 
1

爆炸可能是您的$roles为:"Strategy, Operations"当你explode它使用,它会给你两个元素:"Strategy"" Operations" ...请注意这个词之前的额外空间操作。因此在比较每个元素之前修剪空间。

$roles = "Strategy, Operations"; // lets say $rolepref = array_map('trim', explode(',', $roles)); if (in_array("Strategy", $rolepref)) { echo "yes"; } if (in_array("Operations", $rolepref)) { echo "yes"; }

0

如果发现有精确值in_array返回true。 这可能是你的阵列不完全相同,请尝试用trim()清理它()

下面的代码有效。

$array = [ 
    0 => 'Strategy', 
    1 => 'Operations', 
]; 

if (in_array("Strategy", $array)) 
{ 
    echo "yes s <br />"; 
} 

if (in_array("Operations", $array)) 
{ 
    echo "yes o <br />"; 
}