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

)

2

2 Answers 2

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
        )
)
Sign up to request clarification or add additional context in comments.

Comments

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;
    }
}

2 Comments

Does your solution differ in speed or resources from RomanPerekhrests version?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.