PHP in_array object comparing?

后端 未结 8 1160
终归单人心
终归单人心 2020-12-17 08:37

Can the in_array function compare objects?

For example, I have an array of objects and I want to add them distinctly to another array. Is it possible t

相关标签:
8条回答
  • 2020-12-17 09:40

    See http://php.net/manual/en/function.spl-object-hash.php

    if ( ! array_key_exists( spl_object_hash( $obj ), $objects ) ) {
        $objects[ spl_object_hash( $obj ) ] = $obj;
    }
    

    Cheers

    0 讨论(0)
  • 2020-12-17 09:42

    There's numerous ways you can do this as you can see. I just thought I would add another one. I don't know why, but when working with object arrays I like to use the array functions which use callbacks.

    If your objects have any sort of identifier, which they should if you want to test them for duplication, the following will work:

    $found = array_filter($uniqueObjects, function($uniqueObject) use ($object) {
        return $uniqueObject->id == $object->id
    });
    
    if (!$found) {
        $uniqueObjects[] = $object;
    }
    

    $object is the object you're looking for, and $uniqueObjects is the array of objects you're searching to see if it exists. Just match uniqueObject and object on an identifying property, such as an id.

    0 讨论(0)
提交回复
热议问题