dongshai1944 2017-09-21 00:26
浏览 55
已采纳

PHP在条件语句中比较两个数组

I have two arrays and I want to compare the first with the second array. I have an IF statement and it currently does two checks:

  1. It checks to see if there are any rows from my query
  2. If the above passes, then I want to traverse the array values of the first array and compare it with the second array. I want to traverse through all the names first array (index 0-9) and compare it with the first name of the second array (index 0). Keep doing the same thing until we've compared all the indices 0-9 on the first array with all indices 0-9 of the second array.
  3. Finally, if there is a match I want to exit my PHP script, else if there is no match I continue to do to stuff.

I have tried using the in_array() function and that works, but only with a single variable. Something like this in_array($firstArray[0], $secondArray) works. Something like this:

    if(mysqli_num_rows($result) > 0 && in_array($firstArray[0], $secondArray)){
        exit("exiting now!");
    } 
    else {
        echo "continue to do stuff...";
    }

However, when I put the whole array in the inArray, it won't work. Like this:

in_array($firstArray, $secondArray)

How can I achieve this?

  • 写回答

2条回答 默认 最新

  • doudong4532 2017-09-21 00:42
    关注

    You can use array_intersect if you want to know if they intersect, you can use array_diff to see if the two arrays have any differences.

    if(mysqli_num_rows($result) > 0 && !array_diff($firstArray, $secondArray)){
           exit("exiting now!");
    } else {
           echo "continue to do stuff...";
    }
    

    Example:

    <?php
    $array1 = array (1,2,3,4);
    $array2 = array (3,2,1,5);
    $array3 = array_diff($array1, $array2);
    $array4 = array_intersect($array1, $array2);
    echo "<pre>";
    echo "Array 1
     ";
    print_r($array1);
    echo "Array 2
     ";
    print_r($array2);
    
    echo "Arrays Difference 
     ";
    print_r($array3);
    echo "Arrays intersect 
     ";
    print_r($array4);
    echo "</pre>";
    ?>
    

    Output:

    Array 1
     Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
    )
    Array 2
     Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 5
    )
    Arrays Difference 
     Array
    (
        [3] => 4
    )
    Arrays intersect 
     Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?