2013-10-28 77 views
0
$array1=["joe","bob"]; 
$array2=["tom","bill"]; 
$array3=["dan","mary"]; 

我想打印出每個組合的結果..像(joe,tom,dan),(joe,tom,mary),每個組合只挑選1個數組。等等,直到沒有更多的組合。在此之後,我想將它們張貼到我的網站上的3張張表格中。我知道如何做到這一點,但我被困在這個組合部分。從數組中查找組合

很難解釋..希望你明白..

+0

重複 被允許。 ? –

+0

是的,我相信排列對我來說是正確的。 – user2318029

回答

0

可以使用3循環:

$combinations = new ArrayObject(); 
foreach ($array1 as $name1) { 
    foreach ($array2 as $name2) { 
     foreach ($array3 as $name3) { 
      $combinations->append(array($name1, $name2, $name3)); 
     } 
    } 
} 
+0

var_dump($ combinations);它給了我一個大網格(http://gyazo.com/459a17ed0e456ec598e6fb3cb65cd77d)。任何方式我可以回聲它作爲一個數組每個組合,因爲我想用cURL發佈每個數組? – user2318029

+0

它是一個數組數組。每個數組都是一個組合[name1,name2,name3]。它已經是每個組合的一個數組:'$ combinations [0]'這是第一個組合,'$ combinations [1]'第二個等等。 您可以用「foreach」 ){print join($ c,「,」)。 「\ n」 個; }' – LeartS

+0

你是一個拯救生命的人。你能解釋append()嗎?我不明白php.net的解釋 – user2318029

0

如果沒有信譽是不允許

<?php 

$array1=["joe","bob"]; 
$array2=["tom","bill"]; 
$array3=["dan","mary"]; 

$arr = array_merge($array1,$array2,$array3); 
$result = array(); 

function noRepeatation($arr, $temp_string, &$collect) { 
    if ($temp_string != "") 
     $collect []= $temp_string; 

    for ($i=0; $i<sizeof($arr);$i++) { 
     $arrcopy = $arr; 
     $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element 
     if (sizeof($arrcopy) > 0) { 
      noRepeatation($arrcopy, $temp_string ." " . $elem[0], $collect); 
     } else { 
      $collect []= $temp_string. " " . $elem[0]; 
     } 
    } 
} 

$collect = array(); 
noRepeatation($arr, "", $collect); 
print_r($collect); 
?> 

當聲譽被允許

<?php 
$array1=["joe","bob"]; 
$array2=["tom","bill"]; 
$array3=["dan","mary"]; 

$arr = array_merge($array1,$array2,$array3); 
$result = array(); 

function repeatation($arr, $level, &$result, $curr=array()) { 
    for($i = 0; $i < count($arr); $i++) { 
     $new = array_merge($curr, array($arr[$i])); 
     if($level == 1) { 
      sort($new); 
      if (!in_array($new, $result)) { 
       $result[] = $new;   
      } 
     } else { 
      repeatation($arr, $level - 1, $result, $new); 
     } 
    } 
} 

for ($i = 0; $i<count($arr); $i++) { 
    repeatation($arr, $i+1, $result); 
} 

foreach ($result as $arr) { 
    echo join(" ", $arr) . '<br>'; 
} 
?> 
+0

你們都很好!我希望我能給你兩個正確的答案! – user2318029

+0

@ user2318029你也可以upvote,如果你想 –

+0

相信我我試過..我需要15的聲譽。 – user2318029