How to Efficiently Deduplicate a PHP Multi-Dimensional Array Based on a Specific Key?

DDD
Release: 2024-11-25 13:13:15
Original
366 people have browsed it

How to Efficiently Deduplicate a PHP Multi-Dimensional Array Based on a Specific Key?

PHP Multi-Dimensional Array: Deduplicating Based on a Specific Value

Question:

Given a multi-dimensional array, how do you efficiently remove sub-arrays containing duplicate values for a particular key?

Problem Statement:

Consider the following multi-dimensional array:

Array
(
[0] => Array
    (
        [0] => dave
        [1] => jones
        [2] => [email protected]
    )

[1] => Array
    (
        [0] => john
        [1] => jones
        [2] => [email protected]

    )

[2] => Array
    (
        [0] => bruce
        [1] => finkle
        [2] => [email protected]
    )
)
Copy after login

The task is to remove any sub-arrays where the email address (index 2) appears more than once. In this example, it would result in removing either the first or third sub-array.

Solution:

A straightforward solution involves using array uniqueness to eliminate duplicate email addresses:

$newArr = array();
foreach ($array as $val) {
    $newArr[$val[2]] = $val;    
}
$array = array_values($newArr);
Copy after login

This solution leverages the fact that array keys in PHP are unique. By using the email address as the array key, it ensures that only the last occurrence of a particular email address is retained in the resulting array.

By using array_values() at the end, we reset the array indexes to consecutive numbers, while maintaining the deduplicated data.

Note:

  1. The solution presented prioritizes the last occurrence of the email address. If you prefer to prioritize the first occurrence, reverse the order of the array before iterating through it using array_reverse().
  2. The indexes in the resulting array may be rearranged. This is not a major concern if you do not rely on specific indexes.

The above is the detailed content of How to Efficiently Deduplicate a PHP Multi-Dimensional Array 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template