如何在键值对前添加Laravel Eloquent Collection数组?

Mat*_*cki 9 php arrays laravel eloquent laravel-5

我从数据库中取出一些东西:

$foo = $this->fooRepository->all()->lists('name', 'id');
Run Code Online (Sandbox Code Playgroud)

我明白了:

Collection {#506 ?
  #items: array:9 [?
    "9c436867-afe9-4234-a849-253aea4f602c" => "aaa"
    "d250102b-1370-40d0-99c5-7e5bfd0a15e4" => "sss"
    "7342f212-083b-458d-8af8-24986bbb627d" => "ddd"
    "029c53ce-dc16-49fd-8d83-9d8270d9ff37" => "fff"
    "3add6a37-72e2-4054-853e-9ed8addbf3ea" => "ggg"
    "28f5a9ac-014e-4f22-bda8-e2d5b1f48273" => "hhh"
    "94fccb2c-d732-4369-9bf7-78925797e578" => "jjj"
    "5b494994-93f0-406e-b420-aceb7b6111d7" => "kkk"
    "22a7824a-c6eb-45e7-b9c5-e40c134e3ac8" => "lll"
  ]
}
Run Code Online (Sandbox Code Playgroud)

完善.稍后将此集合传递到Form::select填充选择/选项下拉列表.

我想在这个集合前加上另一个键值对,其中键是空字符串,值将包含" 选择内容 "之类的文本.

我可以追加:

$foo[''] = 'Choose something…';

所以我明白了

Collection {#506 ?
  #items: array:10 [?
    "9c436867-afe9-4234-a849-253aea4f602c" => "aaa"
    "d250102b-1370-40d0-99c5-7e5bfd0a15e4" => "sss"
    "7342f212-083b-458d-8af8-24986bbb627d" => "ddd"
    "029c53ce-dc16-49fd-8d83-9d8270d9ff37" => "fff"
    "3add6a37-72e2-4054-853e-9ed8addbf3ea" => "ggg"
    "28f5a9ac-014e-4f22-bda8-e2d5b1f48273" => "hhh"
    "94fccb2c-d732-4369-9bf7-78925797e578" => "jjj"
    "5b494994-93f0-406e-b420-aceb7b6111d7" => "kkk"
    "22a7824a-c6eb-45e7-b9c5-e40c134e3ac8" => "lll"
    "" => "Choose something…"
  ]
}
Run Code Online (Sandbox Code Playgroud)

但不知道我怎么能把它作为集合的第一个元素.我根本无法使用,array_merge因为我正在处理实例Illuminate\Database\Eloquent\Collection而不是数组,所以这个答案是行不通的.

任何提示?谢谢.

Jos*_*ber 31

$foo = ['' => 'Choose something…'] + $foo->all();
Run Code Online (Sandbox Code Playgroud)

如果您$foo必须是集合实例,只需将其再次包装在集合中:

$foo = collect(['' => 'Choose something…'] + $foo->all());
Run Code Online (Sandbox Code Playgroud)

我向laravel提交了一份PR,允许你传递密钥prepend.如果您使用的是Laravel 5.1.24或更高版本,现在可以执行以下操作:

$foo = $this->fooRepository->all()
            ->lists('name', 'id')
            ->prepend('Choose something…', '');
Run Code Online (Sandbox Code Playgroud)

更高版本的Laravel已将lists方法重命名为pluck.如果您使用的是相对现代版的Laravel,请pluck改用:

$foo = $this->fooRepository->all()
            ->pluck('name', 'id')
            ->prepend('Choose something…', '');
Run Code Online (Sandbox Code Playgroud)