It is trivial to reverse and array. So before processing the array, call array_reverse()
on it:
/** flip it to keep the last one instead of the first one **/
$array = array_reverse($array);
Then at the end you can reverse it again if ordering is an issue:
/** Answer Code ends here **/
/** flip it back now to get the original order **/
$array = array_reverse($array);
So put all together looks like this:
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);
echo "Original array:\n";
print_r($array);
/** flip it to keep the last one instead of the first one **/
$array = array_reverse($array);
/** Answer Code begins here **/
// Build temporary array for array_unique
$tmp = array();
foreach($array as $k => $v)
$tmp[$k] = $v->name;
// Find duplicates in temporary array
$tmp = array_unique($tmp);
// Remove the duplicates from original array
foreach($array as $k => $v) {
if (!array_key_exists($k, $tmp))
unset($array[$k]);
}
/** Answer Code ends here **/
/** flip it back now to get the original order **/
$array = array_reverse($array);
echo "After removing duplicates\n";
echo "<pre>".print_r($array, 1);
produces the following output
Array
(
[0] => my_obj Object
(
[term_id] => 23
[name] => Assasination
[slug] => assasination
)
[1] => my_obj Object
(
[term_id] => 15
[name] => Campaign Finance
[slug] => campaign-finance-good-government-political-reform
)
)