如何在Laravel中动态交叉加入?

问题描述

我想创建类似此图片的产品变体。

enter image description here

我已经尝试使用可以正常工作的静态数据。

$collection = collect(["XL","XXL"]);
return $collection->crossJoin(["1kg","2kg"],["Red","Green"]);

但是我想动态创建它。我已经尝试过这种方式。

$collections = [];
foreach ($request->options as $key => $option) {
  if($key == 0) continue;
  array_push($collections,$option["option_values"]);
}

return $collection->crossJoin($collections);

它的返回像这样的图像。那不是我想要的。我发现问题是$ collections是一个新数组和该数组中的选项值。这样它就返回了。但是我不能解决这个问题。

enter image description here

我有我的请求数据。

enter image description here

解决方法

您在正确的轨道上。以我的方式看,您需要像这样的东西:

// 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);

这种(...$options)会爆炸数组中的所有元素,并将它们设置为参数。

某些人可能会告诉您使用函数call_user_func_array,它使您可以将函数的参数作为数组来调用,就像...

call_user_func_array('some_function',['argument1','argument2']);

很遗憾,我从未使用过此功能。如果有更多经验的人可以实施它,我想知道它将如何实现。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...