Re: Unique items in an array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 12/15/2011 6:24 AM, Marc Guay wrote:
>> Assuming you want to make things unique based on the "contact_first_name" field,
>> how would you decide which record to keep?  The first one you run in to, the
>> last one you come across, or some other criteria?
> 
> The unique field is actually the contact_id.
> 
> Marc
> 

Marc,

If that is the case, can you explain to us how you got the two entries in the
array to begin with?  If this is from a DB query, then it should probably be
address else where.  If it was loaded from a text file, it should be handled
differently.

No matter how it was created, you could always build a method (if the dataset
isn't too large) that would filter things out.

Given your example array, I would do something like this:

<?php

$oldDataSet = array(
  array(
    "contact_id" => "356",
    "contact_first_name" => "Marc",
  ),
  array(
    "contact_id" => "247",
    "contact_first_name" => "Marc",
  ),
  array(
    "contact_id" => "356",
    "contact_first_name" => "Marc",
  ),
);

$newDataSet = array();

foreach ( $oldDataSet AS $k => $entry ) {
  $newDataSet[$entry['contact_id']] = $entry;
  unset($oldDataSet[$k]);
}

print_r($newDataSet);

?>

This would result in something like this:

Array
(
    [356] => Array
        (
            [contact_id] => 356
            [contact_first_name] => Marc
        )

    [247] => Array
        (
            [contact_id] => 247
            [contact_first_name] => Marc
        )

)

Give it a try, should do what you are wanting.

-- 
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/
http://www.bendsource.com/

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux