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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.