[ create a new paste ] login | about

Link: http://codepad.org/9nCJwsvg    [ raw code | output | fork ]

PHP, pasted on Jun 21:
<?php

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;  
}

$input = array(  
    array(  
        'id'    => 123,  
        'ean'   => '1234567890123'  
    ),  
    array(  
        'id'    => 123,   
        'ean'   => '4852950174938'  
    ),  
    array(  
        'id'    => 123,  
        'ean'   => '1234567890123'  
    ),  
);  

$input = arrayUnique($input);

print_r($input);

?>


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array
(
    [0] => Array
        (
            [id] => 123
            [ean] => 1234567890123
        )

    [1] => Array
        (
            [id] => 123
            [ean] => 4852950174938
        )

)


Create a new paste based on this one


Comments: