How to create dynamic combination with php?

Refresh

March 2019

Views

0 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']],
 ]

1 answers

1

For what i understand, you have to combine the arrays of properties into one array of object.

I have to leave now, but if you need a explanation leave a comment and i updated the answers

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

function runFor($arr ,&$array, $keys,$index,&$positions){
    foreach ($arr[$keys[$index]] as $key => $espec){
        $positions[$keys[$index]] = $key;
        if($index + 1 < count($keys)){
            runFor($arr,$array,$keys, $index+1,$positions);
        }else{
            $item = (object)[];
            foreach ($keys as $key){
                $item->$key = $arr[$key][$positions[$key]]['name'];
            }
            array_push($array,$item);
        }
        unset($positions[$keys[$index]]);
    }
}


$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
    array_push($combo,json_encode($item));
}
var_dump($combo);