note 59967 deleted from function.array-unique by nlopess

From: Date: Wed, 21 Dec 2005 20:22:01 +0000
Subject: note 59967 deleted from function.array-unique by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-100545@lists.php.net to get a copy of this message
Note Submitter: memandeemail at gmail dot com ---- I have loaded an array with the results of a database query. The Fields are 'FirstName' and 'LastName'. I would like to find a way to contactenate the two fields, and then return only unique values for the array. For example, if the database query returns three instances of a record with the FirstName John and the LastName Smith in two distinct fields, I would like to build a new array that would contain all the original fields, but with John Smith in it only once. /** * The same thing than implode function, but return the keys so * * <code> * $_GET = array('id' => '4587','with' => 'key'); * ... * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key * ... * </code> * * @param string $glue Oque colocar entre as chave => valor * @param array $pieces Valores * @param string $hifen Separar chave da array do valor * @return string * @author memandeemail@gmail.com */ function implode_with_key($glue = null, $pieces, $hifen = ',') { $return = null; foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv; return substr($return,1); } /** * Return unique values from a tree of values * * @param array $array_tree * @return array * @author memandeemail@gmail.com */ function array_unique_tree($array_tree) { $will_return = array(); $vtemp = array(); foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'='); foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue]; return $will_return; } $problem = array_fill(0,3, array('FirstName' => 'John', 'LastName' => 'Smith') ); $problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita'); $problem[] = array('FirstName' => 'John', 'LastName' => 'Tom'); print_r($problem); print_r(array_unique_tree($problem)); Thanks for Colin Campbell, about the interesting problem.

« previous php.notes (#100545) next »