Home >Backend Development >PHP Tutorial >How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 09:34:10342browse

How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?

Removing Duplicates from Multi-Dimensional PHP Arrays

In PHP, working with multi-dimensional arrays often involves the need to eliminate duplicate elements. This can be particularly useful when dealing with large datasets where identical values may appear in multiple sub-arrays.

Consider the following example, where we have a 2D array with sub-arrays containing name, email, and other information:

$array = [
    [
        'name' => 'Dave',
        'email' => 'dave@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Bruce',
        'email' => 'bruce@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
];

In this example, we have a duplicate entry with the same email address ('john@example.com'). To remove the duplicate sub-array, we can utilize the uniqueness of array indexes using the following snippet:

$newArr = [];
foreach ($array as $val) {
    $newArr[$val['email']] = $val; 
}
$array = array_values($newArr);

By iterating through the sub-arrays and using the email address as the key for the new array, we overwrite any duplicate values with the last matching sub-array. The array_values() function is then used to reset the array indexes, resulting in a deduplicated array:

$array = [
    [
        'name' => 'Dave',
        'email' => 'dave@example.com',
    ],
    [
        'name' => 'John',
        'email' => 'john@example.com',
    ],
    [
        'name' => 'Bruce',
        'email' => 'bruce@example.com',
    ],
];

This technique effectively removes duplicate values based on the specified key, leaving us with a deduplicated multi-dimensional array.

The above is the detailed content of How Can I Remove Duplicate Sub-arrays from a Multi-Dimensional PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn