简体   繁体   中英

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::table('users')->select('value1', 'value2', 'value3')

How can I convert my array to pass those values in my select function?

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.

Thanks for any help.

select() can accept an array, so try:

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

This is source code of select() method :

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:

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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