Zend - The PHP Company




Arrays

Add Code


Object-Array Diff  

Type: code fragment
Added by: DaJoker
Entered: 21/08/2003
Last modified: 09/12/2002
Rating: - (fewer than 3 votes)
Views: 4058
Use this simple functino to duplicate the array_diff() or array_diff_assoc() functionality in PHP with arrays of your own objects. This should, in theory, work with any data type. serialize() could maybe even be used to make this obsolete, but who knows...


<?php
//Difference function for arrays of objects (like array_diff()).
function objArrayDiff($base = array(), $b = array())
{
  for(
$ctr1 0$ctr1 count($base); ++$ctr1)
  {
    foreach(
$b as $key1 => $value1)
    {
      if(
$base[$ctr1] == $value1)
      {
        unset(
$b[$key1]);
      }
//End if
    
}//End foreach
  
}//End for
  
return $b;
}
//End function objArrayDiff($base = array(), $b = array())
?>


Usage Example


$obj1 = new my1Class(1, 2, 3);
$obj2 = new my2Class(1, 2, 3);
$obj3 = new my1Class(2, 3, 4);
$obj4 = new my2Class(2, 3, 4);

$a = array($obj1, $obj2, $obj3);

$obj2->set2ndParm(9);

$b = array($obj2, $obj3, $obj4);

$diff = objArrayDiff($a, $b);

print_r($diff);

Output: (sort of)

Array (
    $obj2,
    $obj4
)

The method will detect changes in objects or among them.  Basically, whatever is in the second array that is not in the first is returned regardless of the size/magnitude of the difference.


Rate This Script





Search



This Category All Categories