问题
Following this question I need to put it in a function (maybe recursive) so that I pass in the array variants and it returns a single array with all the variants.
I have an array with the different t-shirt variants like this:
Color: Black, Red, Blue
Size: L, M, XL
...
The variants may differ, more sizes, les colors, or new variants like tissue variants.
I need a function that returns an array with all the iterated variants like this:
0 Color=>Black Size=>L
1 Color=>Black Size=>M
2 Color=>Black Size XL
3 Color=>Red Size=>L
4 Color=>Red Size=>M
..
I can't get around building this final array. Any help is appreciated!
回答1:
You're looking for Mathematical induction. To answer your first question, you'll need something like this, mix and match to suite your needs:
function induction($arrays, $i = 0)
{
if( ! isset($arrays[$i]))
{
return [];
}
if($i == count($arrays) - 1)
{
return $arrays[$i];
}
$temporaryCombination = induction($arrays, $i + 1);
$result = [];
foreach ($arrays[$i] as $value)
{
foreach ($temporaryCombination as $combination)
{
$result[] = is_array($combination)
? array_merge([$value], $combination) : [
$value,
$combination,
];
}
}
return $result;
}
var_dump(induction([$color,$size,$material]));
Coincidently, or not, by answering your first, I've answer this question too, the above function needs just a little tweaking.
回答2:
Something like that should work :
$inventory = array();
foreach($colors as $color){
foreach($sizes as $size){
$inventory[] = array(
'Color' => $color,
'Size' => $size,
),
}
}
回答3:
First loop through the main array say $array then you will get arrays containing the color & size one by one as the loop is iterating. Then you can retrieve the Colors & Sizes of the shirt with the corresponding key/index i.e ['Color'] & ['Size'] and push them to separate new arrays $colors & $size. array_unique() removes duplicate elements from an array.
$colors=[];
$sizes=[];
foreach($array as $arr){
$colors[]=$arr['Color'];
$sizes[]=$arr['Size'];
}
$colors=array_unique($colors)
$sizes=array_unique($sizes)
来源:https://stackoverflow.com/questions/38866706/recursive-function-to-iterate-through-t-shirt-variants