You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP算法实现:过滤LDAP查询结果中的数字块冗余条目

PHP LDAP查询结果冗余CN条目过滤方案

核心需求很明确:如果某个CN条目是另一个包含更多数字块的条目的前缀(比如1.2是1.2.3的前缀),就把这个父级前缀条目过滤掉,只保留最细分的条目。

实现思路

  1. 先把所有CN按分割后的数字块数量从多到少排序——最长的条目先处理,避免短条目先占坑导致长条目被误过滤。
  2. 遍历每个条目,检查当前条目是否是已保留条目的前缀(即有没有已保留的条目是以当前CN.开头的),如果是就判定为冗余,跳过;否则加入结果集。
  3. 最后对结果做自然排序,让输出更符合阅读习惯。

代码实现

// 原始LDAP查询返回的CN数组(示例数据)
$originalCns = [
    "1",
    "1.2",
    "1.2.3",
    "2",
    "2.1",
    "3"
];

function filterRedundantCns($cns) {
    // 先去重(如果有重复条目)
    $cns = array_unique($cns);
    
    // 按数字块数量倒序排序,长条目优先处理
    usort($cns, function($a, $b) {
        $countA = count(explode('.', $a));
        $countB = count(explode('.', $b));
        return $countB - $countA;
    });

    $filtered = [];
    foreach ($cns as $cn) {
        $isRedundant = false;
        // 检查当前条目是否是已保留条目的前缀
        foreach ($filtered as $existing) {
            if (strpos($existing, $cn . '.') === 0) {
                $isRedundant = true;
                break;
            }
        }
        if (!$isRedundant) {
            $filtered[] = $cn;
        }
    }

    // 自然排序,让结果更规整
    natsort($filtered);
    return array_values($filtered);
}

// 执行过滤并输出
$filteredCns = filterRedundantCns($originalCns);
print_r($filteredCns);
// 输出结果:Array ( [0] => 1.2.3 [1] => 2.1 [2] => 3 )

额外说明

  • 不管CN里是数字还是其他字符,只要分割符是.,这个逻辑都能生效,比如处理group.a和group.a.b这类条目。
  • 如果你的LDAP返回结果里有大小写差异的CN,可以先统一转成小写(或大写)再处理,避免漏判。

内容的提问来源于stack exchange,提问作者guillaume zac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:50:10