Creating Combinations of Elements



PHP Snippet 1:

$inputs = explode(',', $request->input('inputs', '')); // eg ['Color','Size']

// now foreach input in inputs, create new input controls combinations
$props = [];
foreach($inputs as $input)
{
    $input_key = strtolower($input);
    if ( !$request->has($input_key) ) continue;
    $input_values = explode(',', $request->input($input_key));
    $props[$input_key] = $input_values;
}
$combinations = make_combinations($props); // NOTE this is destructive, it will destroy the current $props array, copy it if you need it
// now you can handle the combinations as you want

PHP Snippet 2:

// adjust this function to return the information you need
// right now it returns only the names of the combinations
// adjust or add comment on having more information, eg price
function make_combinations($props)
{
    if ( empty($props) ) return [];
    $keys = array_keys($props);
    $key = $keys[0];
    $values = $props[$key];
    unset($props[$key]);  // this prop is being processed, remove it
    $rest =  make_combinations($props); // process the rest
    if ( empty($values) ) return $rest;
    if ( empty($rest) ) return $values;
    $combinations = []
    foreach($rest as $comb)
    {
        foreach($values as $value)
        {
           $combinations[] = $value . '-' . $comb;
        }
    }
    return $combinations;
}