简体   繁体   English

将php数组转换为逗号分隔的字符串列表

[英]Convert php array into a comma separated list of strings

I have the following array: 我有以下数组:

$arr = [
    0 => 'value1',
    1 => 'value2',
    2 => 'value3'
];

The select function of my db class takes arguments in the following format: 我的db类的select函数采用以下格式的参数:

DB::table('users')->select('value1', 'value2', 'value3')

How can I convert my array to pass those values in my select function? 如何转换我的数组以在我的select函数中传递这些值?

I tried implode(',', $arr) and it gives one string with comma separated values, but what I want is not a single string, it's a list of comma separated strings like in the example above. 我尝试了implode(',', $arr)并且它给了一个逗号分隔值的字符串,但我想要的不是单个字符串,它是一个逗号分隔字符串的列表,如上例所示。

Thanks for any help. 谢谢你的帮助。

select() can accept an array, so try: select()可以接受一个数组,所以尝试:

DB::table('users')->select($arr);

This is source code of select() method : 这是select()方法的源代码

public function select($select = null)
{
    ....

    // In this line Laravel checks if $select is an array. If not, it creates an array from arguments.
    $selects = is_array($select) ? $select : func_get_args();

You can do this in Laravel 5.8 as follows: 您可以在Laravel 5.8中执行以下操作:

DB::table('users')->select('username')->pluck('username')->unique()->flatten();

Hope this helps. 希望这可以帮助。

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

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