duaedf6509 2015-02-06 12:02
浏览 108
已采纳

在PHP中从嵌套的foreach中删除数组值

I am essentially trying to compare Array1, with Array2, to find matching rows. However, both arrays have around 14000 rows (from sql table), so I figured it would be logical to delete matching rows in array2 once found, to reduce the number of iterations overall.

It looks something like this:

foreach($array1 as $arrayRow){
    foreach($array2 as $array2Row){
        if($arrayRow['ID'] == $array2Row['ID']{
         $matchfound = 1;
         unset($array2,$array2Row);
        }
    }
}

However seemingly, nothing happens at all when running the above code.

Note: The data for array 1 and 2 come from two separate databases, and I am unable to run a query on both at once (hence having to do this in php)

  • 写回答

5条回答 默认 最新

  • dongliang9576 2015-02-06 12:11
    关注

    It appears that code will unset $array2 itself, and the local copy of the row within your loop ($array2Row). Instead, get the key for the row you want to unset, and unset the entry directly:

    foreach($array1 as $arrayRow){
        foreach($array2 as $key => $array2Row){
            if($arrayRow['ID'] == $array2Row['ID']{
               $matchfound = 1;
               unset($array2[$key]);
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据