PHP - Generate all combinations of items in array

后端 未结 2 1786
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 09:02

I have a PHP array like this...

$myarray = array(
\'red\', \'yellow\', \'green, \'blue\'
);

Order does not matter to me so I think I am trying

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 09:27

    This example below

     $myarray = array( 'red', 'yellow', 'green', 'blue' );
     $finalarray = [];
     for ($i = 0; $i < count($myarray); $i++) {
         for ($j = $i + 1; $j < count($myarray); $j++) {
             $finalarray[] = $myarray[$i];
             $finalarray[] = $myarray[$j];
         }
     }
     print_r($finalarray);
    

    will print this

     Array ( [0] => red [1] => yellow [2] => red [3] => green [4] => red [5] => blue [6] => yellow [7] => green [8] => yellow [9] => blue [10] => green [11] => blue )
    

提交回复
热议问题