列表, 数组 指定规则去重
curMsg->getFundId() == $prevMsg->getFundId()
重复后处理
// 删除哪个元素?
if ($curMsg->created_at > $prevMsg->created_at) {
// 待删除的元素移动到后面
self::swap($list, $i, $dupIdx);
}
可替换部分如上
没有排序,就这样吧
private static function swap(Collection $c, int $i, int $j) {
$tmp = $c->get($i);
$c->offsetSet($i, $c->get($j));
$c->offsetSet($j, $tmp);
}
/**
* 去除fund_id重复, 相同fund_id取最新的记录,删掉旧的记录
* @param Collection $list
* @author mzh@shall-buy.com
* @date 2022-06-21 3:39 PM
*/
private static function msgListUniq(Collection $list)
{
$n = $list->count();
$countDel = 0;
for ($i = 1; $i < $n;) {
$dupIdx = -1;
$swapped = false;
/** @var $curMsg PayMessage */
$curMsg = $list->get($i);
if (empty($curMsg)) {
break;
}
$prevMsg = null;
for ($j = 0; $j < $i; $j++) {
/** @var $prevMsg PayMessage */
$prevMsg = $list->get($j);
if ($curMsg->getFundId() == $prevMsg->getFundId()) {
$dupIdx = $j;
break;
}
}
// 有重复的fund_id
if (0 <= $dupIdx) {
if ($curMsg->created_at > $prevMsg->created_at) {
self::swap($list, $i, $dupIdx);
$swapped = true;
}
for ($k = $i + 1; $k < $n - $countDel; $k++) {
$list->offsetSet($k - 1, $list->get($k));
}
}
if (false == $swapped) {
$i += 1;
} else {
$countDel += 1;
}
}
// 不要循环中unset
while ($countDel > 0) {
$list->offsetUnset($n - $countDel);
$countDel -= 1;
}
}