我正在使用多维数组在脚本中存储一些信息。有数百个额外的密钥,但这是前三个的样子(私人信息被审查):
Array
(
[0] => Array
(
[last_name] => LAST NAME
[first_name] => COLLEEN
[middle_name] => F
[dob] => 00/00/87
[sex] => F
[race] => W
[city] => SOME CITY
)
[1] => Array
(
[last_name] => LAST NAME
[first_name] => COLLEEN
[middle_name] => F
[dob] => 00/00/87
[sex] => F
[race] => W
[city] => SOME CITY
)
[2] => Array
(
[last_name] => LAST NAME
[first_name] => STEPHANIE
[middle_name] => L
[dob] => 00/00/74
[sex] => F
[race] => W
[city] => SOME CITY
)
)
$array[1]
我想消除重复的键值,例如$array[0]
. 为此,我这样做:
function multi_array_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value) {
if (is_array($value)) {
$result[$key] = multi_array_unique($value);
}
}
return $result;
}
$unique_array = multi_array_unique($array);
$unique_array = array_values($unique_array);
现在,这完成了删除数组中所有重复项的出色工作......除了我无法弄清楚的一件小事。这是数组现在的样子:
Array
(
[0] => Array
(
[last_name] => LAST NAME
[first_name] => COLLEEN
[middle_name] => F
[dob] => 00/00/87
[race] => W
[city] => SOME CITY
)
[1] => Array
(
[last_name] => LAST NAME
[first_name] => STEPHANIE
[middle_name] => L
[dob] => 00/00/74
[sex] => F
[race] => W
[city] => SOME CITY
)
[2] => Array
(
[last_name] => LAST NAME
[first_name] => ASIA
[middle_name] => ALIA
[dob] => 00/00/88
[sex] => F
[race] => B
[city] => SOME CITY
)
)
到底$array[0]["sex"]
去哪儿了???这是唯一缺少的一个,我检查了这个数据集中的 93 个键中的每一个。只是$array[0]
缺少["sex"]
钥匙。我完全被难住了。你们有什么想法吗?
编辑:
Ray 能够提供一个可行的解决方案来实现我想要的结果,但我仍然想知道导致原始错误的原因。
这是 Ray 的工作代码(改编成函数):
function multi_array_unique($multi_array)
{
$newArray = array();
foreach($multi_array as $subArray) {
if(!in_array($subArray, $newArray)) {
$newArray[] = $subArray;
}
}
return $newArray;
}