[英]How to compare two array in php
while($row = $update_post->fetch_array()){
//Explodes checkbox values
$res = $row['column_name'];
$field = explode(",", $res);
$arr = array('r1','r2,'r3','r4','r5','r6');
if (in_array($arr, $field)) {
echo "<script>alert('something to do')</script>";
}else{
echo "<script>alert('something to do')</script>";
}
}
如何检查$ arr的值是否等于$ field的值。
先感谢您。
如果你想匹配两个数组而不是你需要在这里使用array_intersect()
。
如果要使用in_array()
检查特定值,则需要在此处使用循环:
<?php
$res = $row['column_name'];
$field = explode(",", $res);
$arr = array('r1','r2','r3','r4','r5','r6');
foreach ($arr as $value) {
if(in_array($value, $field)) {
echo "success";
}
else{
echo "failed";
}
}
?>
根据手册: in_array - 检查数组中是否存在值
另请注意,您的数组中存在语法错误:
$arr = array('r1','r2,'r3','r4','r5','r6'); // missing quote here for r2
更新:
如果你想使用array_intersect()
,你可以像这样检查:
<?php
$arr1 = array('r1','r2');
$arr2 = array('r1','r2','r3','r4','r5','r6');
$result = !empty(array_intersect($arr1, $arr2));
if($result){
echo "true";
}
else{
echo "false";
}
?>
更新2:
如果你想通过使用array_intersect()
检查你得到的值比你可以使用的那样:
<?php
$arr1 = array('r2');
$arr2 = array('r1','r2','r3','r4','r5','r6');
$result = array_intersect($arr1, $arr2);
if(count($result)){
echo "Following ID(s) found: ".implode(",",$result);
}
?>
通过array_intersect比较两个数组然后用count
来检查知道匹配数组值有...
array_intersect
比较两个数组的值,并返回匹配项:
while($row = $update_post->fetch_array()){
//Explodes checkbox values
$res = $row['column_name'];
$field = explode(",", $res);
$arr = array('r1','r2','r3','r4','r5','r6');
if (count(array_intersect($arr, $field)) > 0) {
echo "<script>alert('duplicate array')</script>";
}else{
echo "<script>alert('something to do')</script>";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.