note 38994 modified in function.array-unique by vrana

From: Date: Tue, 17 Aug 2004 14:50:23 +0000
Subject: note 38994 modified in function.array-unique by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80046@lists.php.net to get a copy of this message
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; } ?> --was-- 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' 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; } http://php.net/manual/en/function.array-unique.php

« previous php.notes (#80046) next »