Sha*_*ain 3 collections cross-join laravel
我尝试过使用静态数据,它可以工作。
$collection = collect(["XL", "XXL"]);
return $collection->crossJoin(["1kg", "2kg"], ["Red", "Green"]);
Run Code Online (Sandbox Code Playgroud)
但我想动态地创建它。我已经尝试过这种方式。
$collections = [];
foreach ($request->options as $key => $option) {
if($key == 0) continue;
array_push($collections, $option["option_values"]);
}
return $collection->crossJoin($collections);
Run Code Online (Sandbox Code Playgroud)
它的返回像这样的图像。这并不完全是我想要的。我发现问题是 $collections 是一个新数组以及该数组内的选项值。所以就这样返回了。但我无法解决这个问题。
我已经添加了我的请求数据。
小智 7
你走在正确的轨道上。在我看来,你需要这样的东西:
// all of my options
$options = [];
// Just store all options in the array
// I am going to assume $option["option_values"] is always an array
foreach ($request->options as $key => $option) {
array_push($options, $option["option_values"]);
}
// Get the first element so we can use collections
// and the crossJoin function
$start = array_shift($options);
return collect($start)->crossJoin(...$options);
Run Code Online (Sandbox Code Playgroud)
类型(...$options)分解数组中的所有元素并将它们设置为参数。
有些人可能会告诉您使用该函数call_user_func_array,该函数允许您使用其参数作为数组来调用函数,就像这样......
call_user_func_array('some_function', ['argument1', 'argument2']);
Run Code Online (Sandbox Code Playgroud)
不幸的是我从来没有使用过这个功能。如果有更有经验的人可以实施它,我想知道它会如何完成。