PHP - Generate all combinations of items in array

心已入冬 提交于 2021-02-05 12:24: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 to calculate combinations rather than permutations. I am wanting to get this back...

$finalarray = array(
    'Red', 'Green',
    'Red', 'Yellow',
    'Red', 'Blue',
    'Green', 'Yellow',
    'Green', 'Blue',
    'Yellow', 'Blue'
);

Is there a built in PHP feature for achieving this or is there a way to do it with loops?


回答1:


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.




回答2:


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 )


来源:https://stackoverflow.com/questions/58218440/php-generate-all-combinations-of-items-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!