问题
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