0

所以我有两个带有家庭成员和姓名的关联数组。每个数组都有相同的索引键,但值不同。我需要组合这两个数组,删除重复值,而不是重复键,然后按字母顺序对其进行排序。

到目前为止我有

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);

到目前为止一切顺利,但后来我尝试:

    $Distinct_names = array_unique($array); 

我得到错误注意:数组到字符串的转换。有任何想法吗?谢谢。

4

2 回答 2

1

你不能array_unique()在多维数组上做;array_unique() 会将每个值转换为字符串并对它们进行比较,但它不能将数组转换为字符串 - 它不会产生预期的结果。

我认为你必须比你希望的更聪明一点;如果你给我五分钟,我也许能想出一些办法。:P

这将实现您想要的输出(按字母顺序排列的唯一名称数组),但它是非常快速和肮脏的解决方案:

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

输出:

Array
(
    [0] => Laurie
    [1] => John
    [2] => Jeff
    [3] => Julie
    [5] => Anna
    [6] => Shannon
    [7] => Phillip
    [8] => Mike
    [12] => Kate
)
于 2012-11-16T20:52:59.977 回答
1

尝试:

 $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);
于 2012-11-16T20:56:46.640 回答