How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?

Barbara Streisand
Release: 2024-11-26 22:22:10
Original
943 people have browsed it

How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?

PHP Multidimensional Array: Removing Duplicates Based on Email

Problem:

You have a multidimensional array with subarrays containing name, surname, and email information, as shown below:

$array = [
    [0] => ['dave', 'jones', 'dave.jones@example.com'],
    [1] => ['john', 'jones', 'john.jones@example.com'],
    [2] => ['bruce', 'finkle', 'bruce.finkle@example.com'],
];
Copy after login

You need to remove duplicate subarrays based on the email value.

Solution:

To effectively deduplicate a multidimensional array based on a specific value, we can utilize array indexes' uniqueness. Here's a solution using this approach:

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

Notice:

  • The last match for each email address is retained in the resulting array. To prioritize the first match, reverse the array before iterating through it:
foreach (array_reverse($array) as $val) {
Copy after login
  • The array indexes in the new array may not be consecutive.

The above is the detailed content of How to Remove Duplicate Subarrays from a PHP Multidimensional Array Based on Email?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template