PHP in_array object comparing?

后端 未结 8 1189
终归单人心
终归单人心 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:21

    The in_array function cannot compare objects.

    You should create unique key-value pairs from your objects and only need to compare those keys when inserting a new object into your final array.

    Assuming that each object has an unique id property, a possible solution would be:

    $unique_objects = array();
    
    // $data represents your object collection
    foreach ($data as $item) {
        if (!array_key_exists($item->id, $unique_objects)) {
            $unique_objects[$item->id] = $obj;
        }
    }
    

提交回复
热议问题