douxian6008 2014-09-29 19:24
浏览 48
已采纳

检查数组值是否存在于另一个数组中[关闭]

I have 2 fields in a table

filed1               | filed2
ahmed,join,maya,omar | omar,maya

I get data by 2 array , I want check if Each value in $array1 the present in $array2 or not

in my case : if $array1[omar] present in $array2 or not , if $array1[maya] present in $array2 or not .. elc

That's my code , not worked ...What's wrong in it ?

$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);

foreach($array1 as $value)
{
    if (in_array($value,$array2))
    {
        //true
    }else{
        //false
    }
}

output of array1 :

Array ( [0] => maya [1] => omar [2] => ahmed [3] => join)

output of array2 :

Array ( [0] => omar [1] => maya )

I have known the cause of the problem, not in the code ... Content of the field at the base value of each line separately So used str_replace to delete the line

$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("
","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("
","",$array2);

foreach($array1 as $value)
{
    if (in_array($value,$array2))
    {
        //true
    }else{
        //false
    }
}
  • 写回答

1条回答 默认 最新

  • dongwei8440 2014-09-29 19:33
    关注

    As @MarkBaker said, you want to use array_intersect:

    array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

    In your case:

    $array1 = explode(",",$query[filed1]);
    $array2 = explode(",",$query[filed2]);
    
    $intersect = array_intersect($array1, $array2);
    

    Since you asked, to check if this array is empty or not do the following:

    if (empty($intersect))
        echo 'It is empty';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 VUE项目怎么运行,系统打不开