How to create dynamic combination with php?

Refresh

6 days ago

Views

20 time

1

I have 3 array like

$arr = [
  "color" => [["name"=>"red"]],
  "size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
  "type" => [["name"=>"plastic"]]
]
$combo = array();
    foreach ($arr['size'] as $size) {
        foreach($arr['color'] as $color){
           foreach ($arr['type'] as $type) {
               $variant =  json_encode(['size' => $size->name, 'color' => 
                                   $color->name, 'type' => $type->name]);
               array_push($combo,$variant);
           }
        }
    }
echo $combo;

// result

0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"

It works properly but but there is can be less or more variants. How can I handle this. For example

$arr = [
   "size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
   "type" => [["name"=>"plastic"]]
]

Or

 $arr = [
    "color" => [["name"=>"red"]],
    "size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
    "type" => [["name"=>"plastic"]],
    "brand" => [['name' => 'something']],
 ]

0 answers