[英]better way to write nested foreach loop, multiple array comparison php
I have 2 multidimensional arrays. 我有2个多维数组。 I run the first one through a foreach
loop to gain data from it. 我通过foreach
循环运行第一个循环以从中获取数据。 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. 然后运行第二foreach
中的第一个创建一个嵌套循环foreach
第二内侧loop.then foreach
循环我运行一个if语句的值从第一阵列比较第二阵列,并显示一些输出,其工作原理,但我有点关注长时间运行。 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
The complexity of two-nested-foreach solution is O(n * k)
, where n = len(array1)
and k = len(array2)
. 两次嵌套的每个解决方案的复杂度为O(n * k)
,其中n = len(array1)
和k = len(array2)
。 However you can achieve a smaller complexity O(n + k)
via using hash tables (assoc arrays in PHP world). 但是,您可以通过使用哈希表(PHP世界中的关联数组O(n + k)
来实现较小的复杂度O(n + k)
)。
$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 aa small number. 因此,您可以看到解决方案的复杂度为O(k + n*t)
,其中t
是一个小数。
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. 当然,仅当两个数组的长度都很大时,此技巧才有意义,否则简单的嵌套foreach也是一个很好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.