簡體   English   中英

將php數組轉換為逗號分隔的字符串列表

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

我有以下數組:

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

我的db類的select函數采用以下格式的參數:

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

如何轉換我的數組以在我的select函數中傳遞這些值?

我嘗試了implode(',', $arr)並且它給了一個逗號分隔值的字符串,但我想要的不是單個字符串,它是一個逗號分隔字符串的列表,如上例所示。

謝謝你的幫助。

select()可以接受一個數組,所以嘗試:

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

這是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();

您可以在Laravel 5.8中執行以下操作:

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM