0

So I have two associative arrays with family members and names. Each array have the same index key, but different values. I need to combine the two arrays, remove duplicate values, not duplicate keys, then sort it alphabetical.

So far I have

Array1 = array(
    "Grandma"=>"Laurie", 
    "Grandpa"=>"John",
     "Uncle"=>"Jeff", 
     "Aunt"=>"Julie", 
     "Cousin1"=>"Julie",
     "Cousin2"=>"Anna");
$Array2 = array(
    "Grandma"=>"Shannon", 
    "Grandpa"=>"Phillip",
     "Uncle"=>"Mike", 
     "Aunt"=>"Laurie", 
     "Cousin1"=>"Anna",
     "Cousin2"=>"Jeff",
     "Cousin3"=>"Kate"); 
//Combine the arrays
$array = array_merge_recursive($Mother_side, $Father_side);

So far so good, but then I try:

    $Distinct_names = array_unique($array); 

and I get errors Notice: Array to string conversion. Any ideas? Thanks.

user1781482
  • 623
  • 3
  • 15
  • 24

2 Answers2

1

You can't do array_unique() on a multi-dimensional array; array_unique() will convert each value to a string and do a comparison on them, but it can't convert an array to a string - it wouldn't produce the expected result.

I think you will have to be a bit more clever than you were hoping; if you give me five minutes I might be able to come up with something. :P

This will achieve the output you want (an array of unique names in alphabetical order), but it's pretty quick and dirty solution:

$names = array();
foreach ($Array1 as $name) $names[] = $name;
foreach ($Array2 as $name) $names[] = $name;
$names = array_unique($names);
asort($names);
print_r($names);

output:

Array
(
    [0] => Laurie
    [1] => John
    [2] => Jeff
    [3] => Julie
    [5] => Anna
    [6] => Shannon
    [7] => Phillip
    [8] => Mike
    [12] => Kate
)
Maccath
  • 3,936
  • 4
  • 28
  • 42
1

Try:

 $array1 = array(
"Grandma"=>"Laurie", 
"Grandpa"=>"John",
 "Uncle"=>"Jeff", 
 "Aunt"=>"Julie", 
 "Cousin1"=>"Julie",
 "Cousin2"=>"Anna");

$array2 = array(
"Grandma"=>"Shannon", 
"Grandpa"=>"Phillip",
 "Uncle"=>"Mike", 
 "Aunt"=>"Laurie", 
 "Cousin1"=>"Anna",
 "Cousin2"=>"Jeff",
 "Cousin3"=>"Kate"); 

 //Combine the arrays
 $array = array_merge_recursive($array1, $array2);

 function multi_arr_unique($array)
{
$distinct = array_map("unserialize", array_unique(array_map("serialize", $array)));

foreach ($distinct as $k => $v)
{
 if ( is_array($v) )
 {
  $distinct[$k] = multi_arr_unique($v);
 }
}

return $distinct;
}

 multi_arr_unique($distinct);
Teena Thomas
  • 5,139
  • 1
  • 13
  • 17