简体   繁体   English

PHP - 仅使用特定值的唯一数组

[英]PHP - Array unique only using specific values

I have a PHP array that looks like this... 我有一个看起来像这样的PHP数组...

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... 如果我像这样使用array_unique ...

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... 它删除了正确的副本[3],但我正在寻找一种方法来忽略[id]并只匹配[date]和[value],这样我的输出就像这样......

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

)

array_reduce + array_values() solution: array_reduce + array_values()解决方案:

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

Iterate over your array and get a key as concatenation of 'date' and 'value' fields. 迭代您的数组并获取一个键作为'date''value'字段的串联。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM