PHP从数组生成3个组合

时间:2016-12-27 10:49:43

标签: php arrays combinations

我将结合以下数组: 该数组将与自身结合

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

1 个答案:

答案 0 :(得分: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);