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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...