dongwusang0314 2014-03-18 12:09
浏览 85

循环遍历多维数组,检查PHP中的重复值的特定键

I have a multi dimensional array that I have got from a database and I want to check this array for duplicate data and store it in another array of duplicates. my code is as follows

    //create temp array
    $tmp = array();

    foreach ($matchingarray as $nameKey => $match) {
          // loop through and stoe the contents of that array to another so i can compare
          $tmp[] = $match;
    }
     // create an array to store duplicates
    $duplicatesArray = array();
    // if the temp array is not empty then loop through both arrays 
    if (! empty($tmp)) {
        foreach ($tmp as $key => $tmpvalue) {
            foreach ($matchingarray as $key => $match) {
               // if a key name is the same in both arrays then add it tothe duplicates array
               if ($tmpvalue['name'] == $match['name']) {
                   $duplicatesArray = $match;
                   }
                }
            }
        }
       //count how many are duplicates
       $dups = count($duplicatesArray);

What I would like to know is this the right logic?

  • 写回答

2条回答 默认 最新

  • doubailian4459 2014-03-18 12:32
    关注

    I will take where Igoel left off

    there is 1 error and also 1 suggest that i will make.

    Error: you cannot reuse $key twice in the foreach because they will override.

    Suggestion as what Igoel stated: your best bet for duplicate effectively is to use sql. SQL is faster at processing than looping through arrays. Don't forget you need to load the data into memory and thats costly.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示