crossJoi-6ren">
gpt4 book ai didi

laravel - 如何在 Laravel 中动态交叉连接?

转载 作者:行者123 更新时间:2023-12-02 19:16:33 25 4
gpt4 key购买 nike

我想创建像这张图片这样的产品变体: 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

我有 dd 我的请求数据。

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']);

不幸的是我从来没有使用过这个功能。如果有更有经验的人可以实现它,我想知道它是如何完成的。

关于laravel - 如何在 Laravel 中动态交叉连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63631114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com