Home >Backend Development >PHP Tutorial >How Can I Deduplicate a Multi-Dimensional PHP Array Based on a Specific Value?

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

DDD
DDDOriginal
2024-11-24 13:15:13705browse

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

Deduplicating Multi-Dimensional Arrays Based on Specific Values in PHP

This article addresses the issue of removing duplicate entries from a two-dimensional array based solely on a specific value within each nested array.

Problem Description

The provided array contains sub-arrays with three values: a name, a last name, and an email address. The goal is to remove sub-arrays with duplicate email addresses while preserving the order of the remaining arrays.

Solution

The below approach leverages a common property of PHP arrays: their unique indexes.

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

This solution involves creating a new array with email addresses as keys. The value for each key is set to the corresponding sub-array. This uniquely associates each email address with its corresponding sub-array, effectively removing duplicates. The final result is an array with the desired deduplicated sub-arrays, but the indexes may be altered.

The above is the detailed content of How Can I Deduplicate a Multi-Dimensional PHP Array Based on a Specific Value?. 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