【问题标题】:PHP multi-dimensional array find duplicates in specific dimensionsPHP多维数组查找特定维度中的重复项
【发布时间】:2011-10-09 02:57:51
【问题描述】:

我有以下数组:

$masterlist=[$companies][$fieldsofcompany][0][$number]

仅当从 $fieldsofcompany 选择的字段 = 包含数字数组的位置 2 时,才存在第三维。其他位置包含常规变量。第 3 维始终为 0(数字数组)或 Null。位置 4 包含数字。

我想循环访问所有公司并从$masterlist 中删除所有包含重复数字的公司。

我目前的实现是这样的代码:

for($i=0;$i<count($masterlist);$i++)
    {   
        if($masterlist[$i][2][0][0] != null)

        $id = $masterlist[$i][0];

        for($j=0;$j<count($masterlist[$i][2][0]);$j++)
        {
            $number = $masterlist[$i][2][0][$j];

            $query = "INSERT INTO numbers VALUES('$id','$number')";
            mysql_query($query);
        }
    }

将数字和相关 ID 插入到表中。然后我像这样选择唯一的数字:

SELECT ID,number
FROM numbers
GROUP BY number
HAVING (COUNT(number)=1)

这让我觉得非常脑残。我的问题是最好的方法是什么?我不是在寻找代码本身,而是在寻找解决问题的方法。对于那些已经阅读到这里的人,谢谢。

【问题讨论】:

    标签: php mysql arrays multidimensional-array performance


    【解决方案1】:

    对于初学者,您应该在将数据粘贴到数据库之前对其进行修剪。

    保留一个跟踪“数字”的查找表。

    如果号码不在查找表中,则使用它并标记它,否则如果它在查找表中,则可以忽略它。

    使用数组作为查找表,键为“数字”,您可以使用 isset 函数测试该数字之前是否出现过。

    示例伪代码:

    if(!isset($lookupTable[$number])){
        $lookupTable[$number]=1;
        //...Insert into database...
    }
    

    【讨论】:

    • 这可能是我正在寻找的东西,但我会等着看其他人是否想出了不需要额外数组写入的东西。谢谢。
    • @Edgar Velasquez Lim 好吧,如果您的唯一号码少于 1,000,000 个,那么您应该可以使用这种技术。如果您不经常运行此代码,那么它根本不重要。就资源使用而言,使用数组和键查找非常便宜。
    • 同意,在这一点上,我的兴趣比任何事情都更学术。 :)
    • @Edgar Velasquez Lim 在学术上这是最好的技术 ;)
    • 将数字转换为数组键的字符串以使散列变得更昂贵而没有任何充分的理由当然不是最好的技术! :P(你可以用$lookupTable[$number]代替$lookupTable["$number"]
    【解决方案2】:

    现在我想我明白你真正想要什么了,你可能想坚持你的两遍方法但跳过 MySQL 绕道。

    在第一关中,收集数字并复制公司:

    $duplicate_companies = array();
    $number_map = array();
    
    foreach ($masterlist as $index => $company)
    {
        if ($company[2][0][0] === null)
            continue;
    
        foreach ($company[2][0] as $number)
        {
            if (!isset($number_map[$number])
            {
                // We have not seen this number before, associate it
                // with the first company index.
                $number_map[$number] = $index;
            }
            else
            {
                // Both the current company and the one with the index stored
                // in $number_map[$number] are duplicates.
                $duplicate_companies[] = $index;
                $duplicate_companies[] = $number_map[$number];
            }
        }
    }
    

    在第二遍中,从主列表中删除我们找到的重复项:

    foreach (array_unique($duplicate_companies) as $index)
    {
        unset($masterlist[$index]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      相关资源
      最近更新 更多