Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

php - Create a product array with all possible variations

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

Provided array:

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

Expected result:

[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"]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Will output

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...