我有一个看起来像这样的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'
)
(
如果我这样使用array_unique ...
print_r(array_unique($array, SORT_REGULAR));
它删除了正确的副本[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()
解决方案:
$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);
输出:
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
)
)
在您的数组上迭代,并获取键作为'date'
和'value'
字段的串联。如果已经找到此键 - 跳过数组值:
$pairs = [];
$new_values = [];
foreach ($array as $item) {
$key = $item['date'] . $item['value'];
if (empty($pairs[$key])) {
$pairs[$key] = 1;
$new_values[] = $item;
}
}