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] ) )
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);
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:
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!