脚本宝典收集整理的这篇文章主要介绍了比较PHP中两个数组中元素对的所有可能组合,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
所以基本上我有2个坐标数组:
$classA = [ new Point(1,1),new Point(1,2),new Point(3,3),5) ]; $classB = [ new Point(4,new Point(5,new Point(4,new Point(6,6) ];
我需要遍历这些数组并且每次获得2对点(一对由来自classA的点和来自classB的另一个点).获得所有可能的组合非常重要.一旦特定点在一对中,它就不能存在于另一对中.
例如,前两对将是:
$pair1 = [$a[0],$b[0]]; $pair2 = [$a[1],$b[1]];
为了更好地解释自己,这就是我需要的:
当第一对包含[1,1],[4,1]时,另一对的所有可能组合都以黄色突出显示.
到目前为止,这就是我所拥有的:
$classA = [ new Point(1,3)]; $classB = [ new Point(4,1)]; $combinations = []; $pair1 = []; $pair2 = []; $n = count($classA); $m = count($classB); for ($i=0; $i<$n; $i++){ for ($j=0; $j<$m; $j++){ $pair1 = [ $classA[$i],$classB[$j] ]; for ($z=0; $z<$n; $z++){ if($z != $i && $z != $j){ for ($y=0; $y<$m; $y++){ if($y != $i && $y != $j){ $pair2 = [ $classA[$z],$classB[$y] ]; $combinations[] = [$pair1,$pair2]; } } } } } }
除了效率低下,这给了我很多重复,有没有办法只获得独特的组合?
$allCombinations = Array(); foreach($classA as $value) { $column = Array(); foreach($classB as $bPart) { $column[] = Array($bPart,$value); } $allCombinations[] = $column; } $possibleCombinations = Array(); $sizeA = count($classA); $sizeB = count($classB); for($a = 0; $a < $sizeA; $a++) { $column = Array(); for($b = 0; $b < $sizeB; $b++) { $temp = $allCombinations; for($i = 0;$i < $sizeA;$i++) { $temp[$a][$i] = null; } for($i = 0;$i < $sizeB;$i++) { $temp[$i][$b] = null; } // for $classA[$a],$classB[$b] possible combinations are in temp Now $column[] = $temp; } $possibleCombinations[] = $column; }
现在,在$possibleCombinations中,您可以看到给定A / B索引的可能组合
在第一个循环中,它只是创建所有可能的组合,
在第二个循环中,它将首先得到A和B值,复制所有组合数组,然后将A列和B行值设置为null(因为它们不能使用,对吧?),最后这个可能的组合存储在$temp中并添加到$possibleCombinations,
例:
$ab = Array($classA[$i],$classB[$j]); $possibleCombinationsForAB = $possibleCombinations[$i,$j];
以上是脚本宝典为你收集整理的比较PHP中两个数组中元素对的所有可能组合全部内容,希望文章能够帮你解决比较PHP中两个数组中元素对的所有可能组合所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。