douciwang6819
2014-06-06 07:41
浏览 249
已采纳

php检查2个数组是否包含相同的值但是顺序不同

Is there a quick way in php to check if 2 arrays contain the same items while the order can be different.

This works for integer arrays How to check if two indexed arrays have same values even if the order is not same in PHP?

//these must be considered equal
array(1,2,3);
array(2,1,3);
array(3,1,2);

//However it must also be possible for strings
array("foo", "bar");
array("bar", "foo");

图片转代码服务由CSDN问答提供 功能建议

有没有一种快速的方式在php中检查2个数组是否包含相同的项目,而顺序可以不同。< / p>

这适用于整数数组如果两个索引数组是否具有相同的值,即使PHP中的顺序不相同,也是如此? < pre> //这些必须被认为是相等的 array(1,2,3); array(2,1,3); array(3,1,2); //然而它 对于字符串 array(“foo”,“bar”); array(“bar”,“foo”); 也必须是可能的

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dougan7657 2014-06-06 08:10
    已采纳

    I found a pretty nice solution myself.

    $ar1 = array("hello","world","foo");//equals
    $ar2 = array("world","foo","hello");//equals
    $ar3 = array("hello","world","bar");//not equal
    
    $ar4 = array();
    //Add all items to a single array
    $ar4 = array_merge($ar1, $ar2);//equal 
    //OR
    $ar4 = array_merge($ar1, $ar3);//not equal
    //Remove all duplicates
    //$ar4 = array_unique($ar4); edited due to comment below
    $ar4 = array_flip($ar4);
    //if you want to user $ar4 later flip it again, its still faster than unique
    $ar4 = array_flip($ar4);
    
    $c1 = count($ar1);// = 3
    $c4 = count($ar4);// = 3 when the arrays were equal and is > 3 if not
    
    if($c1 === $c4){ //CODE }
    

    So for short this is

    $ar1 = array("hello","world","foo");
    $ar2 = array("world","foo","hello");
    $ar4 = array_merge($ar1, $ar2);
    //$ar4 = array_unique($ar4); edited due to comment below
    $ar4 = array_flip($ar4); 
    if(count($ar1) === count($ar4)){ //code }
    
    点赞 打赏 评论
  • dongzhi9032 2014-06-06 07:44

    use this

    1. Sort both the array

      sort($arr1);
      sort($arr2);
      
    2. Compare both by converting them to string - any of the following way.

      echo (implode(" ", $arr1) == implode(" ",$arr2))? "true":"false";
      /* or */
      echo (print_r($arr1,true) == print_r($arr2,true))? "true":"false";
      
    点赞 打赏 评论
  • douweida2669 2014-06-06 07:52

    use this

    $is_equal = (count($arr1)==count($arr2)) && !count(array_diff($arr1, $arr2));
    
    点赞 打赏 评论
  • duan20145 2019-05-22 13:33

    You can sort arrays and then compare them:

    function arrays_are_equal($arr1, $arr2) {
        sort($arr1);
        sort($arr2);
    
        return $arr1 == $arr2;
    }
    
    $arr1 = [1, 2, 3, 4];
    $arr2 = [2, 3, 1, 4];
    
    arrays_are_equal($arr1, $arr2); // true
    
    点赞 打赏 评论

相关推荐 更多相似问题