我正在尝试创建一个程序来检查数组中是否有任何可用的信息
<?php
$fnames = array("Patrick","Janjan","Nico");
$mnames = array("Dasal","Agustino","Macatangay");
$lnames = array("Paredes","Fung","Acedillo");
$names = array($fnames,$mnames,$lnames);
if(in_array("Patrick",$names)){
echo "It exists";
}
else{
echo "Doesn't exists";
}
?>
输出始终不存在
答案 0 :(得分:1)
尝试单个数组,而不是多数组
<?php
$fnames = array("Patrick","Janjan","Nico");
$mnames = array("Dasal","Agustino","Macatangay");
$lnames = array("Paredes","Fung","Acedillo");
$search = 'Patrick';
if(in_array($search,$fnames) || in_array($search,$mnames) || in_array($search,$lnames)){
echo "It exists";
}
else{
echo "Doesn't exists";
}
?>
答案 1 :(得分:0)
使用array_merge
代替array
:
$fnames = array("Patrick","Janjan","Nico");
$mnames = array("Dasal","Agustino","Macatangay");
$lnames = array("Paredes","Fung","Acedillo");
$names = array_merge($fnames,$mnames,$lnames); // Notice array_merge here.
if(in_array("Patrick",$names)){
echo "It exists";
}
else{
echo "Doesn't exists";
}
答案 2 :(得分:0)
您创建了一个嵌套数组,因此您必须以不同方式访问它。 想象一下当你把它写成一个变量时会发生什么:
$names = array(
array("Patrick","Janjan","Nico"),
array("Dasal","Agustino","Macatangay"),
array("Paredes","Fung","Acedillo")
);
如您所见,外部数组中有三个数组。要解决您的问题,您可以使用array_merge()
,从三个阵列中创建一个数组:
$names = array_merge($fnames, $mnames, $lnames);
答案 3 :(得分:0)
您也可以使用array_intersect 因为我们知道&#34; patrick&#34;将成为一个数组的子阵列,我们可以用[[&#34; Patrick&#34;]]找到它。
$fnames = array("Patrick","Janjan","Nico");
$mnames = array("Dasal","Agustino","Macatangay");
$lnames = array("Paredes","Fung","Acedillo");
$names = array($fnames,$mnames,$lnames);
if(array_intersect($names, [["Patrick"]])){
echo "It exists";
}
else{
echo "Doesn't exists";
}
答案 4 :(得分:-1)
<?php
$fnames = array("Patrick","Janjan","Nico");
$mnames = array("Dasal","Agustino","Macatangay");
$lnames = array("Paredes","Fung","Acedillo");
$names = array($fnames,$mnames,$lnames);
if (in_array("Patrick",$names[0]))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
这样可以找到输出匹配...