note 38994 deleted from function.array-unique by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 17:25:38 +0000 |
| Subject: | note 38994 deleted from function.array-unique by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176200@lists.php.net to get a copy of this message | ||
Note Submitter:
----
this simple function is similar based on to the function unique_multi_array posted by tru at
ascribedata dot com, but will work for objects rather than arrays. use 2d objects. Its eg useful to
work with mysql queries since in recent versions, the DISTINCT option in mysql selects will only
work when selecting a single (not more) row.
eg.
foo_obj[0]: name: 'tom', age: '20'
foo_obj[1]: name: 'paul', age: '66'
foo_obj[2]: name: 'tom', age: '23'
foo_obj = DistinctOn ($foo_obj, $item) will return
foo_obj[0]: name: 'tom', age: '20'
foo_obj[1]: name: 'paul', age: '66'
<?php
function DistinctOn ($obj, $item) {
$out = array();
$list = array();
foreach ($obj as $key=>$so) {
if (!in_array($so->$item, $list)) {
$list[] = $so->$item;
$out[$key] = $so;
}
}
return $out;
}
?>