Creating Combinations of Elements

ぃ、小莉子 提交于 2019-12-08 02:52:22

You would need to have a fixed input which represents the other inputs.

For example inputs then using the input names given in inputs field (in your example they are Color and Size) you can adjust your current code to use them. For example to get you started:

$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

Then have a utility recursive function make_combinations() (you can make it a controller method if you need to and call as $this->make_combinations($props) also update below code from make_combinations(..) to $this->make_combinations(..) ) for example:

// 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!