Home >Backend Development >PHP Tutorial >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!