【问题标题】:What is the most efficient way to remove all the elements of one array from another array?从另一个数组中删除一个数组的所有元素的最有效方法是什么?
【发布时间】:2010-11-29 20:35:59
【问题描述】:

我有两个数组,数组 A 包含一个长列表,其中包含一些我想要删除的元素。数组 B 是我希望从数组 A 中删除的那些元素的完整列表。

实现这一目标的最有效方法是什么?

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    array_diff 是显而易见的答案,但既然您要求最有效的方法,这里有一个测试

    $big = range(1, 90000);
    $remove = range(500, 600);
    
    $ts = microtime(true);
    $result = array_diff($big, $remove);
    printf("%.2f\n", microtime(true) - $ts);
    
    $ts = microtime(true);
    $map = array_flip($remove);
    $result = array();
    foreach($big as $e)
        if(!isset($map[$e]))
            $result[] = $e;
    printf("%.2f\n", microtime(true) - $ts);
    

    在我的机器上打印

    0.67
    0.03
    

    因此,基于散列查找的简单循环比 array_diff 快大约 20 倍。

    【讨论】:

    • 我想反对这个答案,因为内存使用或 array_diff 以某种方式更好地执行操作......但我想不出任何准确的东西。荣誉,现在去告诉 php 开发人员让 array_diff 更快。
    【解决方案2】:

    使用array_diff()

    【讨论】:

      【解决方案3】:

      manual 中,它给出了array_dif() 这个例子:

      <?php
      $array1 = array("a" => "green", "red", "blue", "red");
      $array2 = array("b" => "green", "yellow", "red");
      $result = array_diff($array1, $array2);
      
      print_r($result);
      ?>
      

      输出:

      Array
      (
          [1] => blue
      )
      

      返回一个包含所有 来自 array1 的条目不是 存在于任何其他数组中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-04
        • 2011-04-09
        • 2018-03-31
        • 1970-01-01
        • 1970-01-01
        • 2016-09-19
        • 2013-11-26
        相关资源
        最近更新 更多