PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to remove from a multidimensional array all duplicate elements including the original?

 May 16, 2022     arrays, multidimensional-array, php     No comments   

Issue

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
        )
)

Solution

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



Answered By - nice_dev
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing