1

I have the following Associative Array below, and I wish to remove from the $filtered_results or $results the duplicated values based on the nid (number_id) field.

The solution I came up with, was to do a foreach loop, populate the new array with the key unique value that I wish and then return the array_values of that new array.

Is there a more elegant solution to tackle this problem ?

The order is irrelevant ( Replacing or keeping the current value);

Solution 1: Replacing the current value for the next.

$filtered_results = [];
foreach ($results as $k => $v) {
    $filtered_results[ $v['nid'] ] = $v ;
}
return  array_values ( $filtered_results ) ;

Solution 2: Keeping the first value found.

$filtered_results = [];
foreach ($results as $k => $v) {
    if ( isset( $filtered_results[ $v['nid'] ] )) {
        continue;
    }
    $filtered_results[ $v['nid'] ] = $v ;
}

Associative Array

$results = [
    [
        "date" => "2019-03-09",
        "name" => "NameOne",
        "phone" => "56784678",
        "nid" => 1,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameTwo",
        "phone" => "123123123",
        "nid" => 2,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameThree",
        "phone" => "6784568",
        "nid" => 3,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameFour",
        "phone" => "90909090",
        "nid" => 2,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameFive",
        "phone" => "3456356",
        "nid" => 1,
    ],
];

Filtered Results

$filtered_results = [
    [
        "date" => "2019-03-09",
        "name" => "NameThree",
        "phone" => "6784568",
        "nid" => 3,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameFour",
        "phone" => "90909090",
        "nid" => 2,
    ],
    [
        "date" => "2019-03-09",
        "name" => "NameFive",
        "phone" => "3456356",
        "nid" => 1,
    ],
]

Since is a duplicated question, the best solution I have found is :

array_values(array_column($results,NULL,'nid'))

Demo : https://onlinephp.io/c/fe78a

rocket_moon
  • 309
  • 4
  • 18
  • Both solutions are fine. – Barmar May 09 '22 at 21:25
  • You can use array_column without the other array functions the given answers show. The first part of your Solution 1 code can be directly replaced with `$filtered_results = array_column($results, null, 'nid');` – Don't Panic May 09 '22 at 22:03

2 Answers2

0
return array_intersect_key($results, array_unique(array_column($results, 'nid')));
Guido Faecke
  • 644
  • 1
  • 3
  • 7
0

use this :

$filtered_results = array_combine(array_column($results, 'nid'), $results);
Naro
  • 800
  • 6
  • 11