Voting

: one plus seven?
(Example: nine)

The Note You're Voting On

webmaster at jukkis dot net
17 years ago
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.

<< Back to user notes page

To Top