2016-12-27 124 views
-4

3組合,我將以下數組結合起來: 這個陣列會與自身結合PHP生成從陣列

Array (

[0] => Array 

    (
     [0] => 1 
     [1] => 2 
    ) 

[1] => Array 
    (
     [0] => 1 
     [1] => 3 
    ) 

[2] => Array 
    (
     [0] => 1 
     [1] => 4 
    ) 

[3] => Array 
    (
     [0] => 2 
     [1] => 3 
    ) 

[4] => Array 
    (
     [0] => 2 
     [1] => 4 
    ) 

[5] => Array 
    (
     [0] => 3 
     [1] => 4 
    ) 
); 

後組合會產生這樣的陣列:

Array (

[0] => Array 
    (
     [0] => 1 
     [1] => 2 
     [2] => 3 
    ) 

[1] => Array 
    (
     [0] => 1 
     [1] => 2 
     [2] => 4 
    ) 

[2] => Array 
    (
     [0] => 2 
     [1] => 3 
     [2] => 4 
    ) 

); 

例如從1.2與1.3組合將產生1,2,3或1,2與1,4 = 1,2,4

+0

我試過了,但結果是太多和不規則。謝謝 –

+0

使組合 –

+0

它應該只返回3個嵌套項目(如上所示)? – RomanPerekhrest

回答

0

希望你想要這樣。所以你需要檢查條件索引數組連接,並且索引不檢查推動價值

$my_Arr = array( 

     array(1,2), 
     array(1,3), 
     array(1,4), 
     array(2,3), 
     array(2,4), 
     array(3,4) 
    ); 

echo "<pre>"; 
print_r($my_Arr); 

echo "  -------------------------   <br> "; 

    $elements = sizeof($my_Arr); 
    $first_num = ''; 
    $second_num = ''; 
    for ($i=0; $i < $elements; $i++) { 
     $subelements = sizeof($my_Arr[$i]); 
     if($subelements < 4){ 
     for ($j=0; $j < $subelements ; $j++) { 

     if($j == 0){ 
       $first_num =$my_Arr[$i][$j]; 

     } 

     if($j == 1){ 
      $second_num =$my_Arr[$i][$j]; 

     } 

      if($first_num !=null && $second_num != null){ 

       for ($k=0; $k < $elements; $k++) { 
      for ($l=0; $l < $subelements ; $l++) { 
       if($first_num == $my_Arr[$k][$l] && $second_num!=$my_Arr[$k][$l+1]){ 

        if (!in_array($my_Arr[$k][$l+1],$my_Arr[$i])) { 
         array_push($my_Arr[$i], $my_Arr[$k][$l+1]); 
        } 

        } 
       } 


       } 

      } 


      } 
     } 

    } 

echo "<pre>"; 
print_r($my_Arr);