开发者

PHP providing a closure to determine uniqueness of an item in an array

Quick question: is there a way to provide a closure in PHP to some equivalent function to the array_unique function so that you can specify your own comparison closure to be used when comparing two items in the array? I have an array of class instances (which may contain duplicates) and want to tell PHP to use particular logic to determine uniqueness.

PHP provides this with sorting using the usort()开发者_StackOverflow中文版 method - just wondering if it is also available for uniqueness checks. Thanks!


there is array_filter that you can apply a callback to each element in an array and return true/false of whether to keep that value in the returning array. Here is a comment using array_filter to remove duplicates in an array.


I couldn't find exactly what you are looking for but i thought maybe it wouldn't be too tough to write your own function...

$a = new StdClass;
$b = new StdClass;
$c = new StdClass;
$d = new StdClass;

$a->a = 1;
$b->a = 1;
$c->c = 1;
$d->c = 1;

$objects = array( $a,$b,$c,$d );

function custom_array_unique( array $objects ) {

    foreach( $objects as $k =>$object ) {
        foreach( $objects as $k2 => $object2 ) {

            if ( $k !== $k2 && $object == $object2 ) {
                unset( $objects[$k] );
            }

        }
    }
    return $objects;
}

print_r( custom_array_unique($objects));


Array
(
    [1] => stdClass Object
        (
            [a] => 1
        )

    [3] => stdClass Object
        (
            [c] => 1
        )

)


The manual page for array_unique() doesn't provide any links to a callback version, and there isn't a function in the list of links on the left called array_uunique() (which is what such a function should be called if it follows the naming convention of the other array sorting functions - but then PHP isn't very reliable when it comes to function naming conventions).

You could add this functionality yourself using a double foreach loop:

$uniqueness_fails = false;
foreach ( $myarray as $keyA => $valueA ) {
    foreach ( $myarray as $keyB => $valueB ) {
        if ( $keyA != $keyB and my_equality_function($valueA, $valueB) ) {
            $uniqueness_fails = true;
            break 2;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜