创建具有所有可能变化的产品阵列 [英] Create a product array with all possible variations

查看:63
本文介绍了创建具有所有可能变化的产品阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生产具有产品所有变体的阵列.可以有无限数量的属性和变体.

I'm trying to produce an array with all variations of a product. There can be an unlimited amount of attributes and variations.

提供的数组:

["Shirt"]           # Product
    ["Color"]       # Attribute
        ["Green"]   # Variation
        ["Red"]
        ["Blue"]
    ["Size"]
        ["Small"]
        ["Medium"]
        ["Large"]

预期结果:

[0]
    ["type" => "Shirt"]
    ["color" => "Green"]
    ["Size" => "Small"]
[1]
    ["type" => "Shirt"]
    ["color" => "Green"]
    ["Size" => "Medium"]
...
[4]
    ["type" => "Shirt"]
    ["color" => "Red"]
    ["Size" => "Medium"]
[4]
    ["type" => "Shirt"]
    ["color" => "Red"]
    ["Size" => "Large"]

我已经尝试过Laravel和PHP的内置函数,但是没有找到成功.我将不胜感激.

I've tried Laravel's and PHP's built-in functions, but haven't found success. I would really appreciate any insight.

推荐答案

使用三个嵌套的 compact 函数来减少代码.)

Use three nested foreach and push to a $result array at the last level. (Here I used the compact function to reduce the code.)

$provided = [
    'Shirt' => [
        'color' => ['green', 'red'],
        'size' => ['Small', 'Medium'],
    ],
]; // Reduced the provided data to reduce the output for sample purposes.

$result = [];

foreach ($provided as $type => $attributes) {
    foreach ($attributes['color'] as $color) {
        foreach ($attributes['size'] as $size) {
            $result[] = compact('type','color','size');
        }
    }
}

var_dump($result);

将输出

array(4) {
  [0]=>
  array(3) {
    ["type"]=>
    string(5) "Shirt"
    ["color"]=>
    string(5) "green"
    ["size"]=>
    string(5) "Small"
  }
  [1]=>
  array(3) {
    ["type"]=>
    string(5) "Shirt"
    ["color"]=>
    string(5) "green"
    ["size"]=>
    string(6) "Medium"
  }
  [2]=>
  array(3) {
    ["type"]=>
    string(5) "Shirt"
    ["color"]=>
    string(3) "red"
    ["size"]=>
    string(5) "Small"
  }
  [3]=>
  array(3) {
    ["type"]=>
    string(5) "Shirt"
    ["color"]=>
    string(3) "red"
    ["size"]=>
    string(6) "Medium"
  }
}

这篇关于创建具有所有可能变化的产品阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆