0

In PHP, how can I loop through an array of objects and check if a certain key value pair are repeated, then remove the object containing repeated value? So in the example below, getting only the highest 5.2 value and removing the other lower 5.2 values.

class Versions {

public $name;
public $version_num;

   public function __construct($name, $version_num) {
        $this->name = $name;
        $this->version_num = $version_num;
    }
}

$versions_array = [];

$version_one = new Versions("5.2", "5.2.1");
$version_two = new Versions("5.3", "5.3.1");
$version_three = new Versions("5.2", "5.2.2");
$version_four = new Versions("5.2", "5.2.3");
$version_five = new Versions("4.0", "4.0.0");

array_push($versions_array, $version_one, $version_two, $version_three, 
$version_four, $version_five);

function my_sort($a,$b) {
 return $a->version_num < $b->version_num;
}

usort($versions_array,'my_sort');
Joe Moran
  • 55
  • 4

1 Answers1

0

Repeated versions can be removed by adding following code at the end of your code.

$unique_array = [];
$current_name = null;

for ($i = 0; $i < count($versions_array); $i++) {
    if ($versions_array[$i]->name != $current_name) {
        array_push($unique_array, $versions_array[$i]);
    }
    $current_name = $versions_array[$i]->name;
}
y15e
  • 159
  • 5