Reputation: 1524
I have an array and in this array are 3 arrays with attributes, sometimes the array can have more or less..
Array
(
[0] => Array
(
[0] => XS
[1] => S
[2] => M
[3] => L
[4] => XL
)
[1] => Array
(
[0] => Black
[1] => Red
[2] => Green
)
[2] => Array
(
[0] => Fitted
[1] => Not Fitted
)
)
And would like to then echo out recursively..
XS Black Fitted
XS Black Not Fitted
XS Red Fitted
XS Red Not Fitted
XS Green Fitted
XS Green Not Fitted
S Black Fitted
S Black Not Fitted
S Red Fitted
S Red Not Fitted
S Green Fitted
S Green Not Fitted
M Black Fitted
... And so on
I do have code but nothing workable to show anything meaningful. Recursion confuses me and can't seem to produce a recursive function in a way that will produce this.. Any help would be appreciated :)
Upvotes: 0
Views: 44
Reputation: 38502
This is what you need to achieve this combination from php associative arrays. I found this useful method on a github gist when I had to do this type of combination from php associative array, Hope this will help you also.
<?php
function get_combinations($arrays) {
$result = array(array());
foreach ($arrays as $property => $property_values) {
$tmp = array();
foreach ($result as $result_item) {
foreach ($property_values as $property_value) {
$tmp[] = array_merge($result_item, array($property => $property_value));
}
}
$result = $tmp;
}
return $result;
}
$array = [['XS','S','M','L','XL'],['Black','Red','Green'],['Fitted','Not Fitted']];
$combinations = get_combinations($array);
/*
print '<pre>';
print_r($combinations);
print '</pe>';
*/
foreach($combinations as $key=>$value){
echo implode(' ', $value)."\n";
}
?>
SEE DEMO: https://eval.in/1040157
Upvotes: 1