Illuminate\Support\Collection 去重 unique 列表去重

列表, 数组 指定规则去重

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值