2015-02-24 17 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陣列組合]的
相關問題