Reputation: 2246
I have few arrays for example:
array(
'color' => array('red', 'blue', ...);
'size' => array('small', 'big', ...);
'temp' => array('hot', 'cold', ...);
...
)
Is there a function so I can get all possible iterations of these arrays ? (and more arrays and values if needed). For example result should be:
array(
0 => array('color'=> 'red', 'size'=>'small', 'temp'=>'hot')
1 => array('color'=> 'red', 'size'=>'small', 'temp'=>'cold')
2 => array('color'=> 'red', 'size'=>'big', 'temp'=>'hot')
3 => array('color'=> 'red', 'size'=>'big', 'temp'=>'cold')
)
... and so on.
Upvotes: 0
Views: 58
Reputation: 76636
Use a recursive approach:
function generateCombinations($array, $start = 0) {
$size = count($array);
if ($size == $start) {
return array('');
}
$result = array();
foreach ($array[$start] as $val) {
foreach (generateCombinations($array, $start + 1, $size) as $last) {
$result[] = $val . ' ' . $last;
}
}
return $result;
}
Usage:
$array = array(
array('red', 'blue'),
array('small', 'big'),
array('hot', 'cold')
);
$result = generateCombinations($array);
print_r($result);
Output:
Array
(
[0] => red small hot
[1] => red small cold
[2] => red big hot
[3] => red big cold
[4] => blue small hot
[5] => blue small cold
[6] => blue big hot
[7] => blue big cold
)
Upvotes: 1