txrandom Posted July 28, 2007 Share Posted July 28, 2007 I've got an array of objects that are instantiated based on an ID, but it's possible that multiple objects of the same ID may be added to an array. I've tried using array_unique to get rid of duplicates, but if the object contains a null data field, it throws some error messages. How do I get PHP to compare objects by a certain field rather than every variable (null or set) declared in an object? Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted July 28, 2007 Share Posted July 28, 2007 http://php.net/oop5.object-comparison Quote Link to comment Share on other sites More sharing options...
Barand Posted July 28, 2007 Share Posted July 28, 2007 try <?php class txrandom { public $id; function __construct ($i) { $this->id = $i; } function __tostring() { return "$this->id<br>" ; } } /** * creating some data */ $txa = array(); for ($i=0; $i<10; $i++) { if ($i==5) $txa[] = new txrandom(null); // throw in a null balue else $txa[] = new txrandom(rand(1,20)); } /** * the processing */ sort($txa); // if id is first class var, it sorts on that // otherwise need custom sort with usort() foreach ($txa as $obj) echo $obj; // see what we start with $prev=-1; $new = array(); foreach ($txa as $obj) { if ($obj->id != $prev) $new[] = $obj; // check for dupe id $prev = $obj->id; } echo '<hr>'; foreach ($new as $obj) echo $obj; // see what we end with ?> Quote Link to comment Share on other sites More sharing options...
txrandom Posted July 28, 2007 Author Share Posted July 28, 2007 Thanks Barand. Should array_unique() not be used to remove unique objects? It seems like it's not using tostring() to compare objects. Quote Link to comment Share on other sites More sharing options...
Barand Posted July 28, 2007 Share Posted July 28, 2007 you said you tried that and it didn't work. PS __tostring() is just to output the object with echo() Quote Link to comment Share on other sites More sharing options...
txrandom Posted July 28, 2007 Author Share Posted July 28, 2007 Ahh makes sense. Thanks again. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.