php - 组合多个数组,以便有多种选择
问题描述
所以假设我有这个数组:
"variants": [
{
"id": 5,
"name": "color",
"item_id": 3,
"created_at": "2018-11-02 15:08:19",
"updated_at": "2018-11-02 15:08:19",
"options": [
{
"id": 13,
"name": "red",
"variant_id": 5,
"created_at": "2018-11-02 15:08:21",
"updated_at": "2018-11-02 15:08:21"
},
{
"id": 14,
"name": "blue",
"variant_id": 5,
"created_at": "2018-11-02 15:08:21",
"updated_at": "2018-11-02 15:08:21"
},
{
"id": 15,
"name": "green",
"variant_id": 5,
"created_at": "2018-11-02 15:08:22",
"updated_at": "2018-11-02 15:08:22"
}
]
},
{
"id": 6,
"name": "size",
"item_id": 3,
"created_at": "2018-11-02 15:08:19",
"updated_at": "2018-11-02 15:08:19",
"options": [
{
"id": 16,
"name": "small",
"variant_id": 6,
"created_at": "2018-11-02 15:08:22",
"updated_at": "2018-11-02 15:08:22"
},
{
"id": 17,
"name": "medium",
"variant_id": 6,
"created_at": "2018-11-02 15:08:22",
"updated_at": "2018-11-02 15:08:22"
},
{
"id": 18,
"name": "large",
"variant_id": 6,
"created_at": "2018-11-02 15:08:22",
"updated_at": "2018-11-02 15:08:22"
}
]
}
]
您将如何组合所有可能性,以便我拥有:红色小号、红色中号、红色大号、蓝色小号、蓝色中号、蓝色大号、绿色小号、绿色中号、绿色大号。此外,数组不一定总是相同的大小。
这个项目是用 PHP 编写的,专门使用 laravel 框架
解决方案
为了适应多种变体:
function getVariants($obj)
{
$variant = array_shift($obj["variants"]); // we use the variants as a stack
$results = array(); // we will store the results here
foreach($variant["options"] AS $k=>$v) // we iterate the current variants
{
if(count($obj["variants"]) > 0) // if we have more variants still
{
$sub = getVariants($obj); // we call getVariants to build next level
foreach($sub AS $sub_v) // iterate over the results of the child level
{
// concatenate whatever came from children to the current names
$results[] = $v["name"]." ".$sub_v;
}
}
else
{
$results[] = $v["name"]; // this is the last variant so we just add the names.
}
}
return $results;
}
这应该适用于所需的任何深度组合。
这段代码的作用是将变体用作处理变体的堆栈,然后如果堆栈更长,仍会调用自身以在下一个级别执行相同的操作。每个级别都返回他们自己和他们的孩子的数组(如果有的话)。
推荐阅读
- sql - 组合表的两列并将其作为由字符分隔的单列返回
- c# - ASP.NET MVC5 自定义身份验证
- xamarin.forms - 如何设置某些图标而不是默认图钉?
- python - 无法缩放 tkinter PhotoImage:_tkinter.TclError:没有足够的可用内存用于图像缓冲区
- certificate - 使用 EV 证书自动进行代码签名
- reactjs - 如何使用 React Router 制作多页和布局(或)容器?
- docker - 在没有 --privileged 标志的情况下访问 Docker 容器中的多个设备
- vb.net - 如何通过索引获取 ListBox 项的 ValueItem 值
- excel - 循环遍历每张表以查找包含值的名称,做某事,再次循环查找新值
- php - 多个 PHP 版本