Home > Article > Backend Development > 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', ], ];
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; } }
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', ], ]
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!