doufangzhang4454 2018-02-18 11:19
浏览 134
已采纳

更好的方法来编写嵌套的foreach循环,多个数组比较php

I have 2 multidimensional arrays. I run the first one through a foreach loop to gain data from it. then run the second foreach loop inside the first creating a nested foreach loop.then inside the second foreach loop I run an if statement to compare a value from the first array to the second array and display some output which works, however I am a little concerned about long run-time. so my question is, is there a cleaner, neater way to write it with a shorter run type:

@foreach($arrayOne as $firstArray)
    @foreach($arrayTwo as $secondArray)
        @if($firstArray['id'] == $secondArray['linkedId'])
            /*output some data*/
        @endif
    @endforeach      
@endforeach
  • 写回答

1条回答 默认 最新

  • dongre1907 2018-02-18 11:48
    关注

    The complexity of two-nested-foreach solution is O(n * k), where n = len(array1) and k = len(array2). However you can achieve a smaller complexity O(n + k) via using hash tables (assoc arrays in PHP world).

    $twoByLinkedId = [];
    foreach ($arrayTwo as $x) {  // K iterations
        if (empty($twoByLinkedId[$x['linkedId']])) {
            $twoByLinkedId[$x['linkedId']] = [];
        }
        array_push($twoByLinkedId[$x['linkedId']], $x);
    }
    
    foreach ($arrayOne as $el) {  // N iterations
        $entries = empty($twoByLinkedId[$el['id']]) 
            ? [] 
            : $twoByLinkedId[$el['id']];
        foreach ($entries as $entry) {  // only few iterations
            /* output $entry */
        }
    }
    

    So you can see that the complexity of the solution is O(k + n*t), where t is a a small number.

    Of course, the trick makes sense only if the lengths of both arrays are really big, otherwise simple nested foreach is a good solution too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下: