如何在Laravel中获取数值数组?
这就是我所拥有的:
$companies = Company::select(['id','name'])->get()->toArray();
这让我回来了:
array:21 [
0 => array:2 [
"id" => 21
"name" => "Cool Company"
]
1 => array:2 [
"id" => 4
"name" => "Bacon Co"
]
....
但我想:
array:21 [
0 => array:2 [
21,
"Cool Company"
]
1 => array:2 [
4,
"Bacon Co"
]
....
答案 0 :(得分:1)
如果你需要这个确切的输出,你可以做
$companies = App\Company::pluck('name', 'id')
->map(function ($name, $id) {
return [$id, $name];
})
->values()
->toArray();
输出:
=> [ [ 4, "Bacon Co", ], [ 21, "Cool Company", ], ]
不确定之后您正在做什么,但可能只是pluck()
的输出就足够了
$companies = App\Company::pluck('name', 'id')->toArray();
=> [ 4 => "Bacon Co", 21 => "Cool Company", ]