In PHP, you can deduplicate objects using built-in functions such as `array_unique` and custom approaches. Below is an example of how to achieve this by converting the objects to an array and then back to objects after removing duplicates.
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$people = [
new Person('Alice', 30),
new Person('Bob', 25),
new Person('Alice', 30), // Duplicate
new Person('Charlie', 35)
];
// Function to deduplicate objects
function deduplicate($people) {
$unique_people = [];
foreach ($people as $person) {
$unique_key = serialize($person); // Serialize object for unique comparison
if (!in_array($unique_key, $unique_people)) {
$unique_people[] = $unique_key;
}
}
return array_map('unserialize', $unique_people); // Unserialize back to objects
}
$deduplicated_people = deduplicate($people);
print_r($deduplicated_people);
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?