简体   繁体   English

发送逗号分隔在 php 和 laravel 的循环中生成的一些数组

[英]send comma separated some array generated in a loop in php and laravel

suppose we have an Object that accept some value as array that is separated by comma:假设我们有一个 Object 接受一些值作为用逗号分隔的数组:

$keyboard = new Keyboard(
            ['value1'],
            ['value2'],
            ['value3'],
            ['value4']
        );

Now I want to fetch some value from database via a loop and send them finally to that object.现在我想通过循环从数据库中获取一些值并将它们最终发送到 object。 but I do not know how can I collect them and send a comma separated list of them.但我不知道如何收集它们并发送逗号分隔的列表。

I write this code But can not get appropriate result from it:我写了这段代码但不能从中得到适当的结果:

$brands = Option::with('translations')->whereHas('attribute', function ($query) {
                    $query->where('type', '=', 'brand');
                })->get();

                $titles = [];
                foreach ($brands as $key => $brand) {
                    $titles [] = array($brand->title_fa);
                }

                $keyboard = new Keyboard(
                    $titles
                );

You can use ... operator to pass parameters.您可以使用...运算符来传递参数。 But check before whether size of an array is proper.但请先检查数组的大小是否合适。

$keyboard = new Keyboard(...$titles);

First I suggest plucking the value that you want and then map them首先我建议采摘你想要的价值然后 map 他们

Look at the Laravel Collection methods to avoid doing unnecessary loops and doing it more fluent看Laravel的收集方法,避免做不必要的循环,做得更流畅

https://laravel.com/docs/7.x/collections https://laravel.com/docs/7.x/collections

$brands = Option::with('translations')->whereHas('attribute', function ($query) {
                    $query->where('type', '=', 'brand');
                })->get()
                  ->pluck('title_fa')
                  ->map(function($brand){ return [$brand]; })->all()

Now you have a $brands array as required现在你有一个$brands需要的数组

So you can pass it as an array or as a Varidic params using the Splat operator as suggested in the other answer因此,您可以按照其他答案中的建议,使用 Splat 运算符将其作为数组或可变参数传递

$keyboard = new Keyboard($brands);
$keyboard = new Keyboard(...$brands);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM