0

I have a large multidimensional array that looks like the below.

I want to remove duplicate arrays based on the ID, however, I am struggling to achieve this.

I want the duplicates to work over the entire array, so you can see that ID 1229873 is a duplicate, in the array 2021-07-07 and 2021-07-09, it should therefore be removed from 2021-07-09

How would I achieve this? array_unique has not worked for me.

$data = array (
'2021-07-07' => 
array (
  0 => 
  array (
    'id' => 5435435,
    'homeID' => 8754,
    'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
    'competition_id' => 5808,
    'matches_completed_minimum' => 12,
  ),
  1 => 
  array (
   'id' => 1229873,
    'homeID' => 8754,
    'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
    'competition_id' => 5808,
    'matches_completed_minimum' => 12,
      ),
),
'2021-07-09' => 
array (
    0 => 
  array (
    'id' => 3243234,
    'homeID' => 8754,
    'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
    'competition_id' => 5808,
    'matches_completed_minimum' => 12,
  ),
  1 => 
  array (
   'id' => 1229873,
    'homeID' => 8754,
    'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
    'competition_id' => 5808,
    'matches_completed_minimum' => 12,
      ),
    ),
     );   
Oxeem
  • 55
  • 7
  • 1
    Does this answer your question? [PHP remove duplicate values from multidimensional array](https://stackoverflow.com/questions/3598298/php-remove-duplicate-values-from-multidimensional-array) – Kinglish Jul 07 '21 at 22:21
  • @Kinglish have you read the answers on that? They are _abysmally_bad. – Sammitch Jul 07 '21 at 22:38
  • @Sammitch - guilty. no - I should have checked, though I know it's a dupe many times over (with better options :)) – Kinglish Jul 07 '21 at 22:41

2 Answers2

0

This is a perfect case for array_uunique()! No wait, scratch that. The PHP devs refused to implement it for the perfectly valid reason of... [shuffles notes] "the function name looks like a typo".

[sets notes on fire]

Anyhow, you just need to iterate over that data, keep track of the IDs you've seen, and remove entries that you've already seen.

$seen = [];

foreach(array_keys($data) as $i) {
    foreach(array_keys($data[$i]) as $j) {
        $id = $data[$i][$j]['id'];
        if( in_array($id, $seen) ) {
            unset($data[$i][$j]);
        } else {
            $seen[] = $id;
        }
    }
}

I've opted for the foreach(array_keys(...) as $x) approach as avoiding PHP references is always the sane choice.

Run it.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
-1

I am Sure That is the way which you want to get the unique array.

$unique = array_map("unserialize", array_unique(array_map("serialize", $data)));
echo "<pre>";
print_r($unique);
echo "</pre>";