note 76769 added to function.array-unique
| From: | webmaster at jukkis dot net | Date: | Mon, 30 Jul 2007 11:08:51 +0000 |
| Subject: | note 76769 added to function.array-unique | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129038@lists.php.net to get a copy of this message | ||
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for
array_filter.
Example:
<?php
/* example object */
class myObj {
public $id;
public $value;
function __construct( $id, $value ) {
$this->id = $id;
$this->value = $value;
}
}
/* callback function */
function uniquecol( $obj ) {
static $idlist = array();
if ( in_array( $obj->id, $idlist ) )
return false;
$idlist[] = $obj->id;
return true;
}
/* a couple of arrays with second array having an element with same id as the first */
$list = array( new myObj( 1, 1 ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );
$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );
?>
In addition, use array_merge( $unique ) to reindex.
----
Server IP: 69.147.83.197
Probable Submitter: 88.115.202.208
----
Manual Page -- http://www.php.net/manual/en/function.array-unique.php
Edit -- https://master.php.net/note/edit/76769
Del: integrated -- https://master.php.net/note/delete/76769/integrated
Del: useless -- https://master.php.net/note/delete/76769/useless
Del: bad code -- https://master.php.net/note/delete/76769/bad+code
Del: spam -- https://master.php.net/note/delete/76769/spam
Del: non-english -- https://master.php.net/note/delete/76769/non-english
Del: in docs -- https://master.php.net/note/delete/76769/in+docs
Del: other reasons-- https://master.php.net/note/delete/76769
Reject -- https://master.php.net/note/reject/76769
Search -- https://master.php.net/manage/user-notes.php