【问题标题】:Convert php array into a comma separated list of strings将php数组转换为逗号分隔的字符串列表
【发布时间】:2016-08-29 14:28:49
【问题描述】:

我有以下数组:

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

我的 db 类的 select 函数采用以下格式的参数:

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

如何转换我的数组以在我的选择函数中传递这些值?

我尝试了implode(',', $arr),它给出了一个带有逗号分隔值的字符串,但我想要的不是一个字符串,而是一个逗号分隔的字符串列表,就像上面的例子一样。

感谢您的帮助。

【问题讨论】:

  • 如果您使用的是现代版本的 PHP,可能是 DB::table('users')->select(...$arr);或者只是DB::table('users')->select($arr),因为 select 方法将接受一个参数数组
  • 一个解决方案:DB::table('users')->select("'".implode("','",$array)."'")

标签: php arrays laravel


【解决方案1】:

select() 可以接受一个数组,所以试试:

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

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

【讨论】:

  • 它实际上“更喜欢”一个数组,太棒了!
【解决方案2】:

你可以在 Laravel 5.8 中这样做:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多