Php 组合多个阵列,以便有多种选择
假设我有一个数组:Php 组合多个阵列,以便有多种选择,php,arrays,laravel,multidimensional-array,Php,Arrays,Laravel,Multidimensional Array,假设我有一个数组: "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,
"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;
}
这应该适用于所需的任何深度的组合
这段代码做了什么?它使用变量作为堆栈处理变量,然后如果堆栈不再调用自己,则在下一个级别上执行相同的操作。每个级别返回一个自身及其子级(如果有)的数组
我们只需在第一个标准上创建一个foreach,在第二个标准上创建第二个foreach。还是关于多重标准的问题?如果是这样的话,使用一个递归函数迭代每个条件(对于条件中的每个值)并为每个迭代调用自己以获得下一个条件。我只是不知道如何在它上面循环。我的意思是,假设有10种不同的变体,每种都有3-7个选项,我如何才能获得每一种可能性?我正在研究laravel集合的映射方法,但我看不到像我刚才描述的那样大的东西的大局。你正在尝试生成笛卡尔积。如果这是从数据库中输出的,您可能可以使用查询生成器来完成。请看这里的crossJoin:所以我昨晚浏览了您的代码,非常流畅。非常感谢你。我也很感激你的评论,它帮了我很大的忙。