从多维数组中删除重复的键 [英] Remove duplicate keys from Multidimensional Array
问题描述
我有一个相当大的数组,包含留言板上所有论坛的数据,不幸的是,我遇到一个问题,我正在为一些键重复输入。这个数组由父母排列在一个层次结构中,这就是为什么它在某些方面变得更深入。
I have a rather large array that contains data for all of the forums on a message board, unfortunately I am running into an issue where I am having repeat entries for some keys. The array is ordered in an hierarchy by parents, which is why it gets deep at some points.
Array
(
[0] => Array
(
[cat_data] => Array()
[forum_data] => Array
(
[2] => Array
(
[subforums] => Array
(
[6] => Array
(
[subforums] => Array
(
[15] => Array()
[16] => Array()
)
)
[7] => Array()
[15] => Array()
[16] => Array()
)
)
[3] => Array()
)
)
)
论坛ID 6被重复为论坛ID 2的子论坛。我需要删除数组中最低级别的重复键。所以在这个例子中,我想保留15和16作为sub的6,但删除它们作为2的sub。
The subforums on the forum id 6 are repeated as subforums for forum id 2. I need to remove the repeated keys that are in the lowest level of the array. So in this example, I would like to keep 15 and 16 as subs of 6 but remove them as subs of 2.
只是一个注释,我正在写一个应用程序板子,我不是生成数组,它是由板生成的,这就是为什么我不能删除重复的数组在创建。
Just a note, I am writing an application for the board, I am not generating the array, it is generated by the board, that is why I can't remove the duplicates while the array is being created.
谢谢您所有的帮助。
推荐答案
应该这样做:
function remove_dup_keys(array &$array) {
$keys = array();
foreach ($array as $key => &$value) {
if (is_array($value)) {
$keys = array_merge($keys, remove_dup_keys($value));
}
}
foreach ($keys as $key) {
if (is_numeric($key) && in_array($key, $keys)) {
unset($array[$key]);
}
}
$keys = array_merge($keys, array_keys($array));
return $keys;
}
remove_dup_keys($yourarray);
你得到:
Array
(
[0] => Array
(
[cat_data] => Array
(
)
[forum_data] => Array
(
[2] => Array
(
[subforums] => Array
(
[6] => Array
(
[subforums] => Array
(
[15] => Array
(
)
[16] => Array
(
)
)
)
[7] => Array
(
)
)
)
[3] => Array
(
)
)
)
)
这篇关于从多维数组中删除重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!