How Can I Deduplicate a Multi-Dimensional Array in PHP Based on a Specific Key?

Barbara Streisand
Release: 2024-11-26 06:56:11
Original
535 people have browsed it

How Can I Deduplicate a Multi-Dimensional Array in PHP Based on a Specific Key?

PHP Multi-Dimensional Array De-Duplication

In PHP, it is possible to remove duplicates from a multi-dimensional array based on the values of a specific key. Consider the following example:

$array = [
    [
        'name' => 'dave',
        'lastname' => 'jones',
        'email' => 'dave.jones@example.com',
    ],
    [
        'name' => 'john',
        'lastname' => 'jones',
        'email' => 'john.jones@example.com',
    ],
    [
        'name' => 'bruce',
        'lastname' => 'finkle',
        'email' => 'bruce.finkle@example.com',
    ],
];
Copy after login

To remove duplicate sub-arrays based on the email key, one can utilize the following approach:

$uniqueArray = array();
foreach ($array as $key => $subarray) {
    if (!isset($uniqueArray[$subarray['email']])) {
        $uniqueArray[$subarray['email']] = $subarray;
    }
}
Copy after login

This method uses the unique indexes of array keys to create a new array ($uniqueArray) with non-duplicate sub-arrays. The resulting array will only contain the following elements:

[
    'dave.jones@example.com' => [
        'name' => 'dave',
        'lastname' => 'jones',
        'email' => 'dave.jones@example.com',
    ],
    'bruce.finkle@example.com' => [
        'name' => 'bruce',
        'lastname' => 'finkle',
        'email' => 'bruce.finkle@example.com',
    ],
]
Copy after login

Note that the order of the keys in the resulting array is arbitrary. If a specific ordering is desired, additional steps may be necessary. This method can be effectively used to de-duplicate multi-dimensional arrays based on arbitrary criteria.

The above is the detailed content of How Can I Deduplicate a Multi-Dimensional Array in PHP Based on a Specific Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template