代码之家  ›  专栏  ›  技术社区  ›  Ben G

关于删除一些特定于数组的php索引

  •  0
  • Ben G  · 技术社区  · 15 年前

    假设我有一个多维数组,有100个子数组。子数组总是至少有3个索引,但可以有更多。我想从大数组中删除所有重复的子数组 . 一个只有两个子数组的数组示例:

    array(array(0 => 'a', 1=> 'b', 2 => 'c', 3 => 'd'), array(0 => 'a', 1=> 'b', 2=> 'c', 3=> 'z'))
    

    我在寻找最优雅/高效的解决方案。

    3 回复  |  直到 15 年前
        1
  •  1
  •   Damien    15 年前
    /**
     * Create Unique Arrays using an md5 hash
     *
     * @param array $array
     * @return array
     */
    function arrayUnique($array, $preserveKeys = false)
    {
        $arrayRewrite = array();
        $arrayHashes = array();
        foreach($array as $key => $item) {
            $hash = md5(serialize($item));
            if (!isset($arrayHashes[$hash])) {
                $arrayHashes[$hash] = $hash;
                if ($preserveKeys) {
                    $arrayRewrite[$key] = $item;
                } else {
                    $arrayRewrite[] = $item;
                }
            }
        }
        return $arrayRewrite;
    }
    
    $uniqueArray = arrayUnique($array);
    var_dump($uniqueArray);
    

    发件人: http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html

    希望有帮助!

    如果有人能帮你编辑,那就更好了!

        2
  •  1
  •   Nick    15 年前

    function firstThree($array)
    {
       $retArray = array();
       array_push($retArray, $array[1], $array[2], $array[3]);
       return $retArray;
    }
    
        3
  •  0
  •   Jon    15 年前

    这会成功的。不是最优雅的例子,因为free函数带有静态变量,但是可以通过使用lambda或回调目标类的实例使其更优雅。

    function filter($subArray) {
        static $seenKeys = null;
        if ($seenKeys === null) {
            $seekKeys = array();
        }
    
        // I 'm just selecting the "three first" indexes here,
        // you can change it to better suit your needs
        $thisKey = serialize(array_slice($subArray, 0, 3));
        if (isset($seenKeys[$thisKey])) {
            return false;
        }
        else {
            return $seenKeys[$thisKey] = true;
        }
    }
    
    $result = array_filter($inputArray, 'filter');
    

    我认为这个例子在不假设每个子数组的前三个项的类型和/或值的情况下,在PHP中运行得最快。如果有这样的假设,那么至少 serialize 电话可以换成更合适的。我想这会大大加快这个过程。

    推荐文章