PHP - Generate all combinations of items in array

后端 未结 2 1785
隐瞒了意图╮
隐瞒了意图╮ 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 )
    
    0 讨论(0)
  • 2021-01-29 09:29

    You can of course with permutation libraries, but that you have to sort every single subarray alphabetically and remove duplicates with array_unique().

    Or you might try to be more cost efficient:

    $myarray = array(
    'red', 'yellow', 'green', 'blue'
    );
    
    $result = [];
    
    while ($item = array_pop($myarray)) {
        foreach($myarray as $couple) {
            $result[] = [$item, $couple];
        }
    }
    
    print_r($result);
    

    First thing is you are reducing a source array every step, and every context should have its copy of array. It means, that if you are willing to encapsulate mechanics in recursive function to generate more that two member arrays, you need to prevent their internal copies from being changed by anything else than array_pop of their own context.

    For the explanation of code above, I'm popping one element off the top of source array, and than iterate over survived element to couple a pair. This way I wont pair "red" with "red", and I wont produce disordered duplicates.

    0 讨论(0)
提交回复
热议问题