I was looking for a good answer to this question and could not find it, so I wrote my own, which will handle this case, and the case when you want to cancel the deletion based on several properties.
$array = DeDupeArrayOfObjectsByProps($array, ['name']);
Here's a common function:
/** * Iterates over the array of objects and looks for matching property values. * If a match is found the later object is removed from the array, which is returned * @param array $objects The objects to iterate over * @param array $props Array of the properties to dedupe on. * If more than one property is specified then all properties must match for it to be deduped. * @return array */ public function DeDupeArrayOfObjectsByProps($objects, $props) { if (empty($objects) || empty($props)) return $objects; $results = array(); foreach ($objects as $object) { $matched = false; foreach ($results as $result) { $matchs = 0; foreach ($props as $prop) { if ($object->$prop == $result->$prop) $matchs++; } if ($matchs == count($props)) { $matched = true; break; } } if (!$matched) $results[] = $object; } return $results; }
Here is the full use for your case:
class my_obj { public $term_id; public $name; public $slug; public function __construct($i, $n, $s) { $this->term_id = $i; $this->name = $n; $this->slug = $s; } } $objA = new my_obj(23, "Assasination", "assasination"); $objB = new my_obj(14, "Campaign Finance", "campaign-finance"); $objC = new my_obj(15, "Campaign Finance", "campaign-finance-good-government-political-reform"); $array = array($objA, $objB, $objC); $array = DeDupeArrayOfObjectsByProps($array, ['name']); var_dump($array);
Nico westerdale
source share