PHP-如何删除多维数组中的重复键

时间:2019-02-11 23:06:33

标签: php multidimensional-array unique

我有一个多维数组,我想删除所有重复的键,但是我已经尝试过但不能使用任何脚本。

以下答案适用于重复值,我想对多维数组中的重复键使用相同的解决方案。

PHP remove duplicate values from multidimensional array

$arr = array(
    "a" => "xxx",
    "b" => "xxx",
    "c" => array(
        "g" => "xxx",
        "a" => "xxx",
        "h" => "xxx",
    ),
    "d" => "xxx",
    "e" => array(
        "i" => array(
            "a" => "xxx",
            "k" => array(
                "l" => "xxx",
                "b" => "xxx",
            ),
        ),
        "j" => "xxx",
    ),
    "f" => "xxx",
);

我想要这个结果:

$arr = array(
    "a" => "xxx",
    "b" => "xxx",
    "c" => array(
        "g" => "xxx",
        "h" => "xxx",
    ),
    "d" => "xxx",
    "e" => array(
        "i" => array(
            "k" => array(
                "l" => "xxx",
            ),
        ),
        "j" => "xxx",
    ),
    "f" => "xxx",
);

我正在尝试通过以下功能解决此问题:

function array_unique_key($array) { 
    $result = array(); 
    foreach (array_unique(array_keys($array)) as $tvalue) {
        if (is_array($tvalue)) {
            $result[$tvalue] = $array[$tvalue]; 
        }
        $result[$tvalue] = $array[$tvalue]; 
    } 
    return $result; 
} 

2 个答案:

答案 0 :(得分:2)

此功能将执行您想要的操作。它递归地遍历数组,寻找已经遇到的键并找到它们的位置,从而从数组中取消设置该元素。请注意,我们通过引用函数传递$array$keys以便可以对其进行更改(感谢@ Don'tPanic指出也需要通过引用引用$keys):

function remove_dup_keys(&$array, &$keys = array()) {
    foreach ($array as $key => &$value) {
        if (in_array($key, $keys)) {
            unset($array[$key]);
        }
        else {
            $keys[] = $key;
        }
    }
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            remove_dup_keys($value, $keys);
        }
    }
}

输出:

Array (
    [a] => xxx
    [b] => xxx
    [c] => Array (
        [g] => xxx
        [h] => xxx
    )
    [d] => xxx
    [e] => Array (
        [i] => Array (
             [k] => Array (
                 [l] => xxx
             )
        )
        [j] => xxx
    )
    [f] => xxx 
)

Demo on 3v4l.org

答案 1 :(得分:2)

如果要保留原始数组,则为另一种选择。

function array_unique_key($input, &$keys = []) {

    // filter any preexisting keys from the input while adding its keys to the set of unique keys

    $input = array_filter($input, function($key) use (&$keys) {
        return isset($keys[$key]) ? false: $keys[$key] = true;
    }, ARRAY_FILTER_USE_KEY);

    // recursively map this function over the remaining values

    return array_map(function($value) use (&$keys) {
        return is_array($value) ? array_unique_key($value, $keys): $value;
    }, $input);

}