2015-02-24 40 views
0
$example1 = array(3, 9, 5, 12); 
$example2 = array(5, 4); 
$example3 = array(8, 2, 4, 7, 3); 

如何在不重复的情况下在这些数组元素之间得到一对一的组合?阵列元素之间一对一无复制

对于$example1应该返回:

3 9 
3 5 
3 12 
9 5 
9 12 
5 12 

$example2: 

5 4 

$example3: 

8 2 
8 4 
8 7 
8 3 
2 4 
2 7 
2 3 
4 7 
4 3 
7 3 

我想:

<?php 

$example3 = array(8, 2, 4, 7, 3); 

foreach ($example3 as $e) { 

    foreach ($example3 as $e2) { 
    if ($e != $e2) { 
     echo $e . ' ' . $e2 . "\n"; 
    } 
    } 

} 

这回我:http://codepad.org/oHQTSy36

但如何排除重复的最好方法?

+0

可能重复(http://stackoverflow.com/questions/3742506/php-array-combinations) – 2015-02-24 11:02:03

+0

@PiotrOlaszewski其中有组合一对一的? – dakajuvi 2015-02-24 11:06:47

回答

0

差不多。但在第二个循环中,您只需选取原始数组的一部分。

array_slice功能可能有帮助。

$example1 = array(3, 9, 5, 12); 

for ($i = 0, $n = count($example1); $i < $n; $i++) { 
    foreach(array_slice($example1, $i+1) as $value) { 
     echo $example1[$i] . ' ' . $value . "\n"; 
    } 
} 
0

这只是另一种获得结果的方法。

for($i=0;$i<count($example1);$i++) 
{ 
    for($j=$i;$j<count($example1);$j++) 
    { 
     if($example1[$i] != $example1[$j]) 
     { 
      echo $example1[$i].'::'.$example1[$j].'<br>'; 
     } 
    } 
} 
[PHP阵列组合]的
相关问题