PHP unique array by value?

后端 未结 6 689
南方客
南方客 2020-12-03 15:22

I have an array in PHP that looks like this:

  [0]=>
       array(2) {
           [\"name\"]=>
              string(9) \"My_item\"
           [\"url\"]         


        
6条回答
  •  不知归路
    2020-12-03 15:35

    Please find this link useful, uses md5 hash to examine the duplicates:

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

    Quick Glimpse:

    /**
     * Create Unique Arrays using an md5 hash
     *
     * @param array $array
     * @return array
     */
    function arrayUnique($array, $preserveKeys = false)
    {
        // Unique Array for return
        $arrayRewrite = array();
        // Array with the md5 hashes
        $arrayHashes = array();
        foreach($array as $key => $item) {
            // Serialize the current element and create a md5 hash
            $hash = md5(serialize($item));
            // If the md5 didn't come up yet, add the element to
            // to arrayRewrite, otherwise drop it
            if (!isset($arrayHashes[$hash])) {
                // Save the current element hash
                $arrayHashes[$hash] = $hash;
                // Add element to the unique Array
                if ($preserveKeys) {
                    $arrayRewrite[$key] = $item;
                } else {
                    $arrayRewrite[] = $item;
                }
            }
        }
        return $arrayRewrite;
    }
    
    $uniqueArray = arrayUnique($array);
    var_dump($uniqueArray);
    

    See the working example here: http://codepad.org/9nCJwsvg

提交回复
热议问题