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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度