Skip to content

Instantly share code, notes, and snippets.

@jtarleton
Created December 7, 2012 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtarleton/4230833 to your computer and use it in GitHub Desktop.
Save jtarleton/4230833 to your computer and use it in GitHub Desktop.
Two approaches to de-duping a multi-dimensional array
/*
* Super Unique
*/
public function super_unique(array $badarray)
{
$goodarray = array();
foreach( $badarray as $ba )
{
$goodarray[ serialize($ba) ] = $ba;
}
$returnarray = array_values($goodarray);
return $returnarray;
/*
$badarray = array(
array('foo','bar'), array('baz','boo'), array('foo','bar'), array('foo','bar'), array('baz','boo'),
array('biz','baa'), array('foo','bar'), array('baz','boo'), array('foo','bar'), array('foo','bar'),
array('boo','baa'), array('foo','bar'), array('foo','bar'), array('baz','boo'), array('fop','bop')
);
*/
$goodarray= array();
$col1_ref = array();
$col2_ref = array();
$q = 0;
foreach( $badarray as $row )
{
$keys = array_keys($row);
$dupeExists = false;
for($j=0; $j < count($col1_ref); $j++)
{
if ( ($col1_ref[$j] == $row[$keys[0]]) && ($col2_ref[$j] == $row[$keys[1]]) )
{
$dupeExists = true;
}
}
if(!$dupeExists)
{
$goodarray[] = $row;
}
$col1_ref[] = $row[$keys[0]];
$col2_ref[] = $row[$keys[1]];
$q++;
}
return $goodarray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment