PHP multidimensional array deduplication

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    There are several ways to achieve deduplication in a PHP multidimensional array. Here are some of the most common methods:

    1. Using array_map and array_unique

    This method involves serializing each element of the array, then using array_unique to remove duplicates, and finally unserialize the elements back to their original form.

    function unique_multidim_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();
       
        foreach($array as $val) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }
    
    $originalArray = [
        ['id' => 1, 'name' => 'John'],
        ['id' => 2, 'name' => 'Paul'],
        ['id' => 1, 'name' => 'John'], // Duplicate
    ];
    
    $result = unique_multidim_array($originalArray, 'id');
    

    2. Using array_reduce

    This method uses array_reduce to iterate over the array and build a new array that doesn't include duplicates.

    $uniqueArray = array_reduce($originalArray, function ($carry, $item) {
        if (!in_array($item, $carry)) {
            $carry[] = $item;
        }
        return $carry;
    }, []);
    

    3. Custom Function

    You can also write a custom function that checks for duplicates based on specific keys in the array.

    function removeDuplicates($array, $key) {
        $temp = [];
        foreach ($array as $v) {
            if (!isset($temp[$v[$key]])) {
                $temp[$v[$key]] = $v;
            }
        }
        return array_values($temp);
    }
    

    4. Using json_encode and json_decode

    This method involves converting array elements to JSON strings, using array_unique, and then converting them back to arrays.

    $uniqueArray = array_map('json_decode', array_unique(array_map('json_encode', $originalArray)));
    

    Each of these methods has its own advantages and is suitable for different scenarios depending on the structure of your array and the criteria for considering an element as a duplicate. Make sure to choose the method that best fits your specific use case.

Leave an answer