Skip to content

Instantly share code, notes, and snippets.

@prcaen
Created August 18, 2011 09:13
Show Gist options
  • Save prcaen/1153708 to your computer and use it in GitHub Desktop.
Save prcaen/1153708 to your computer and use it in GitHub Desktop.
[PHP] - Distinct double in a multi dimensional array
<?php
/**
* Get a distinct multi dimensional array
*
* @param array $array
* array to distinct
* @param string $keySearch
* string key to search double array
* @param boolean $overwrite = false
* boolean to allow values to be overwritten
* @param array $exception = array()
* array of keys to not overwrite if overwrite is true
*
* @return array $result
* Return a multi dimensional array witch has been distinct.
*/
public static function distinctMultiDimensionalArray($array, $keySearch, $overwrite = false, $exception = array())
{
// Check if it's an array
if( !is_array($array) )
return false;
$result = array();
foreach ( $array as $entry )
{
// If email doesn't exist
if ( !isset($result[$entry[$keySearch]]) )
$result[$entry[$keySearch]] = $entry;
else
{
// If email exist
foreach ( $entry as $key => $value )
{
if( !empty($value) )
{
// If not empty value and this value is different from before and you don't want to overwrite values
// Or you want to overwrite values except some keys
if( ( !empty( $result[$entry[$keySearch]][$key] )
&& $result[$entry[$keySearch]][$key] != $value
&& $overwrite == false )
||
( $overwrite == true
&& in_array($key, $exception) ) )
$result[$entry[$keySearch]][$key] = $result[$entry[$keySearch]][$key] . ', ' . $value;
else
$result[$entry[$keySearch]][$key] = $value;
}
}
}
}
$result = array_values($result);
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment