Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...