首页 > 解决方案 > 组合多个数组,以便有多种选择

问题描述

所以假设我有这个数组:

    "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 框架

标签: phparrayslaravelmultidimensional-array

解决方案


为了适应多种变体:

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;
}

这应该适用于所需的任何深度组合。

这段代码的作用是将变体用作处理变体的堆栈,然后如果堆栈更长,仍会调用自身以在下一个级别执行相同的操作。每个级别都返回他们自己和他们的孩子的数组(如果有的话)。

https://en.wikipedia.org/wiki/Recursion_(computer_science)


推荐阅读