1

I have a PHP array that looks like this...

Array
(
    [0] => Array
    (
        [id] => 1
        [value] => 111
        [date] => 'today'
    )

[1] => Array
    (
        [id] => 2
        [value] => 222
        [date] => 'today'
    )

[2] => Array
    (
        [id] => 3
        [value] => 333
        [date] => 'today'
    )

[3] => Array
    (
        [id] => 1
        [value] => 111
        [date] => 'today'
    )

[4] => Array
    (
        [id] => 5
        [value] => 111
        [date] => 'today'
    )

)

If I use array_unique like this...

print_r(array_unique($array, SORT_REGULAR));

It removes the duplicate [3] which is correct, but I am looking for a way to ignore [id] and only match by [date] and [value] so that my output looks like this...

Array
(
    [0] => Array
    (
        [id] => 1
        [value] => 111
        [date] => 'today'
    )

[1] => Array
    (
        [id] => 2
        [value] => 222
        [date] => 'today'
    )

[2] => Array
    (
        [id] => 3
        [value] => 333
        [date] => 'today'
    )

)

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

4

array_reduce + array_values() solution:

$arr = [
    ['id' => 1, 'value' => 111, 'date'=> 'today'],
    ['id' => 2, 'value' => 222, 'date'=> 'today'],
    ['id' => 3, 'value' => 333, 'date'=> 'today'],
    ['id' => 1, 'value' => 111, 'date'=> 'today'],
    ['id' => 5, 'value' => 111, 'date'=> 'today']
    ];

$result = array_values(
    array_reduce($arr, function($r, $a){
        if (!isset($r[$a['value'] . $a['date']])) $r[$a['value'] . $a['date']] = $a;
        return $r;
    }, [])
);

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 111
            [date] => today
        )

    [1] => Array
        (
            [id] => 2
            [value] => 222
            [date] => today
        )

    [2] => Array
        (
            [id] => 3
            [value] => 333
            [date] => today
        )
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

Iterate over your array and get a key as concatenation of 'date' and 'value' fields. If this key has already been found - skip array value:

$pairs = [];
$new_values = [];
foreach ($array as $item) {
    $key = $item['date'] . $item['value'];

    if (empty($pairs[$key])) {
        $pairs[$key] = 1;
        $new_values[] = $item;
    }
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Does your solution differ in speed or resources from RomanPerekhrests version? – fightstarr20 Feb 18 '18 at 18:10
  • You can compare this yourself. But I don't think you will find significant difference. And unless your array has millions of records you won't even feel the difference. – u_mulder Feb 18 '18 at 18:13