Home > Software design >  How to remove from a multidimensional array all duplicate elements including the original?
How to remove from a multidimensional array all duplicate elements including the original?

Time:05-11

I am using php 7.1.

I have seen that to eliminate the duplicate elements it is enough with this

array_unique($array, SORT_REGULAR);

I've also seen this work

array_map("unserialize", array_unique(array_map("serialize", $array)));

But that only deletes the elements that are duplicated from the array, I want to delete those that are duplicated but I don't want it to leave me only 1 without a duplicate, I want it to also delete that original on which it has been based to verify that it is duplicated

How could I do it?

For example i have this

$array = array(
    [0] = array(
        [id] => 1,
        [number] => 12345,
        [date] => 2022-05-09
    )
    [1] = array(
        [id] => 2,
        [number] => 123456,
        [date] => 2022-05-09
    )
    [2] = array(
        [id] => 3,
        [number] => 123456,
        [date] => 2022-05-09
    )
    [3] = array(
        [id] => 3,
        [number] => 123456,
        [date] => 2022-05-09
    )
)

How can i let it become this:?

    $array = array(
        [0] = array(
            [id] => 1,
            [number] => 12345,
            [date] => 2022-05-09
        )
        [1] = array(
            [id] => 2,
            [number] => 123456,
            [date] => 2022-05-09
        )
)

CodePudding user response:

This should be straightforward. Pluck all IDs using array_column and use array_count_values to get counts of occurrences of each ID. Then, use array_filter to filter only unique ones.

<?php

$unique_ids = array_count_values(array_column($array,'id'));
$res = array_filter($array, fn($v) => $unique_ids[$v['id']] === 1);
print_r($res);

Online Demo

  • Related