php compare/diff an array with an array of objects

10,595

Solution 1

Assuming $objects is your array of objects, and $values is your array of values to remove...

You could use a foreach loop if you want to return objects:

$values = array(5, 6);
$objects = array(
    (object) array("id" => 1),
    (object) array("id" => 3),
    (object) array("id" => 5),
    (object) array("id" => 6),
    (object) array("id" => 7)
);
foreach($objects as $key => $object) {
    if(in_array($object->id,$values)) {
        unset($objects[$key]);
    }
}

Live demo (0.008 sec)

If you want to use the diff function itself (that's possible but awkward, less readable and will just return an array of values) you can (as Baba suggested) return the id of the object inline:

$values = array(5, 6);
$objects = array(
    (object) array("id" => 1),
    (object) array("id" => 3),
    (object) array("id" => 5),
    (object) array("id" => 6),
    (object) array("id" => 7)
);
$diff = array_diff(array_map(function ($object) {
    return $object->id;
}, $objects), $values);

Live demo (0.008 sec)

Solution 2

You can try :

$diff = array_diff(array_map(function ($v) {
    return $v->id;
}, $array2), $array1);

See Live DEMO

Solution 3

Loop over the second array and use in_array method to check for existing values in first

$firstArray = array(5, 6);
foreach ($objects as $key => $object) {
    if (in_array($object->id, $firstArray)) {
        unset($objects[$key];
    }
}

Solution 4

For versions older than 5.3

 foreach( $arr_2nd as $key => $val  )
{
   $arr_2nd[$key] = $val->id;
}

array_diff( $arr_1st, $arr_2nd );
Share:
10,595
feub
Author by

feub

PHP developer. Magento and Zend Framework.

Updated on June 25, 2022

Comments

  • feub
    feub almost 2 years

    I have 2 PHP arrays, a simple one:

    array
      0 => int 5
      1 => int 6
    

    and an array of objects:

    array
      0 => 
        object(stdClass)[43]
          public 'id' => int 1
      1 => 
        object(stdClass)[46]
          public 'id' => int 3
      2 => 
        object(stdClass)[43]
          public 'id' => int 5
      3 => 
        object(stdClass)[46]
          public 'id' => int 6
      4 => 
        object(stdClass)[46]
          public 'id' => int 7
    

    I'd like to make a diff of these 2 arrays to eliminate in the second those present in the first. In this example, i don't want the ids 5 and 6 in the second array. But i need help ;>

    Thank you.

    fabien