Jump to content

[SOLVED] Comparing Objects


txrandom

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/62153-solved-comparing-objects/
Share on other sites

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
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.