Hi have problem to merge array
My first array is product options
Second array is product variations
I need to duplicate my option array values while values quantity equal to second array's value quantity.
For Eg:
$inputs = ["Red-S-Cotton", "Blue-Silk-M"];
$keys = ['Color-Size-Material', 'Color-Material-Size'];
in this array's values is equal 2 = 2 But my $keys array's has only one value
$key = ['Color-Size-Material'];
when i tried to merge them i get error because there are not equal.
My array values and value names is changeable and get's randomly. i have code look like this:
function make_combinations($props)
{
if ( empty($props) ) return [];
$keys = array_keys($props);
$key = $keys[0];
$values = $props[$key];
unset($props[$key]);
$rest = make_combinations($props);
if ( empty($values) ) return $rest;
if ( empty($rest) ) return $values;
$combinations = [];
foreach($rest as $comb)
{
foreach($values as $value)
{
$combinations[] = $value . '-' . $comb;
}
}
return $combinations;
}
$inputs = explode(',', $request['option']);
$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);
$as = array(implode('-', $inputs));
$inpu = $combinations;
$keys =$as;
$say = count($inpu);
$say2 = count($keys);
if($say2 < $say) {
$output = array_map(function ($key) use ($inpu, $keys) {
$expKeys = explode('-', $keys[$key]);
$expInputs = explode('-', $inpu[$key]);
return array_combine($expKeys, $expInputs);
}, array_keys($inpu));
dd($output);
}else{
$output = array_map(function ($key) use ($inpu, $keys) {
$expKeys = explode('-', $keys[$key]);
$expInputs = explode('-', $inpu[$key]);
return array_combine($expKeys, $expInputs);
}, array_keys($inpu));
dd($output);
}
$result[] = compact('combinations', 'inputs');
return view('system.modules.variants', compact('result'));
}
my first array's output is:
array:1 [
0 => "Color-Size"
]
Second array's output is:
array:2 [
0 => "Red-S"
1 => "Blue-S"
]
First array may be Color-Size-Material-Type.... Second array may be Red-S-A-Cotton... Please Help Me
I need output like this:
array:2 [
0 => array:2 [
"Color" => "Red"
"Size" => "S"
]
1 => array:2 [
"Color" => "Blue"
"Size" => "S"
]
]
See Question&Answers more detail:os