-
-
Save cereal-s/5c896a161c5e7af52e4b3afde4d27076 to your computer and use it in GitHub Desktop.
PHP: Get all combinations of multiple arrays (preserves keys)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_combinations($arrays) { | |
$result = [[]]; | |
foreach ($arrays as $property => $property_values) { | |
$tmp = []; | |
foreach ($result as $result_item) { | |
foreach ($property_values as $property_value) { | |
$tmp[] = array_merge($result_item, array($property => $property_value)); | |
} | |
} | |
$result = $tmp; | |
} | |
return $result; | |
} | |
$combinations = get_combinations( | |
[ | |
'item1' => ['A', 'B'], | |
'item2' => ['C', 'D'], | |
'item3' => ['E', 'F'], | |
] | |
); | |
print_r($combinations); // 2*2*2 = 8 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array | |
( | |
[0] => Array | |
( | |
[item1] => A | |
[item2] => C | |
[item3] => E | |
) | |
[1] => Array | |
( | |
[item1] => A | |
[item2] => C | |
[item3] => F | |
) | |
[2] => Array | |
( | |
[item1] => A | |
[item2] => D | |
[item3] => E | |
) | |
[3] => Array | |
( | |
[item1] => A | |
[item2] => D | |
[item3] => F | |
) | |
[4] => Array | |
( | |
[item1] => B | |
[item2] => C | |
[item3] => E | |
) | |
[5] => Array | |
( | |
[item1] => B | |
[item2] => C | |
[item3] => F | |
) | |
[6] => Array | |
( | |
[item1] => B | |
[item2] => D | |
[item3] => E | |
) | |
[7] => Array | |
( | |
[item1] => B | |
[item2] => D | |
[item3] => F | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment