问题描述
按照这个问题我需要把它放在一个函数中(可能是递归的),以便我传入数组变体,它返回一个包含所有变体的数组.
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.
我有一个包含不同 T 恤变体的数组,如下所示:
I have an array with the different t-shirt variants like this:
颜色:黑色、红色、蓝色
Color: Black, Red, Blue
尺码: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 颜色=>黑色尺寸=>L
0 Color=>Black Size=>L
1 色=>黑色尺寸=>M
1 Color=>Black Size=>M
2 色=>黑色 XL 码
2 Color=>Black Size XL
3 色=>红色尺寸=>L
3 Color=>Red Size=>L
4 色=>红色尺寸=>M
4 Color=>Red Size=>M
...
我无法绕过构建这个最终数组.任何帮助表示赞赏!
I can't get around building this final array. Any help is appreciated!
推荐答案
您正在寻找 数学归纳法.要回答您的第一个问题,您需要像这样混合搭配以满足您的需求:
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.
这篇关于迭代 T 恤变体的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!