1

I have an object array that looks like this:

Array
(
[0] =>Object
        (
            [ClassScheduleID] => 2263
            [Name] => Workout 1
            [Location] => Object
            (
                [BusinessID] => 1
            )
)
[1] =>Object
        (
            [ClassScheduleID] => 2263
            [Name] => Workout 1
            [Location] => Object
            (
                [BusinessID] => 13
            )
)
[2] =>Object
        (
            [ClassScheduleID] => 2264
            [Name] => Workout 2
            [Location] => Object
            (
                [BusinessID] => 22
            )
)

I am looking to identify that the ClassScheduleID of 2263 is a duplicate, and remove the duplicate entry's entire object from the array. So that I get:

Array
    (
    [0] =>Object
            (
                [ClassScheduleID] => 2263
                [Name] => Workout 1
                [Location] => Object
                (
                    [BusinessID] => 1
                )
    )

    [1] =>Object
            (
                [ClassScheduleID] => 2264
                [Name] => Workout 2
                [Location] => Object
                (
                    [BusinessID] => 22
                )
    )

I tried the solution proposed here

How to remove duplicate values from a multi-dimensional array in PHP

but the count() remained the same

Community
  • 1
  • 1
kylesmith
  • 13
  • 4

2 Answers2

1
$count = 0;
foreach($arrayObj as $key => $value) {
    if ($value['ClassScheduleID'] == 2263) {
        $count++;
    }
    if ($count > 1){
        unset($arrayObj[$key]);
        $count--;
    }
}

It works: http://ideone.com/fork/zrdDtu

Edit: Modified to delete any duplicates:

foreach($arrayObj as $key => $value) {
    $count = 0;
    foreach($arrayObj as $nkey => $nvalue) {
        if ($value['ClassScheduleID'] == $nvalue['ClassScheduleID']) {
            $count++;
        }
        if ($count > 1){
            unset($arrayObj[$key]);
            $count--;
        }
    }
}

var_dump($arrayObj);

See it here: http://ideone.com/fork/85RCst

Nu Gnoj Mik
  • 994
  • 3
  • 10
  • 25
  • sorry, i guess i should have been more specific. i want it to remove ANY duplicate entries, the 2263 was just for demonstration – kylesmith Apr 22 '14 at 18:30
0
function get_unique_array($array)
{
   $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

   foreach ($result as $key => $value)
   {
      if ( is_array($value) )
      {
        $result[$key] = get_unique_array($value);
      }
   }

   return $result;
}

Demo: http://3v4l.org/WOTHi#v430

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47