Search code examples
phpmultidimensional-arrayunique

PHP - How to Remove Duplicate Keys in Multidimensional Array


I have a multidimensional Array I want to delete all duplicate keys, I've tried but not working any script.

Following answer is working for duplicate values and I want same solution for duplicate keys in multidimensional array.

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

I want this result:

$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",
);

I'm trying to solve this issue by this function:

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

Solution

  • Another option if you want to keep the original array.

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