Laravel - get DB result without table column name

六眼飞鱼酱① 提交于 2019-12-20 01:43:41

问题


I wanted to have the result with only the values not with the table column name in Laravel 4.2. For example,

$recs = DB::table('table_name')
        ->select('id', 'title')
        ->get();

the result is

array(2) {
  [0]=>
  object(stdClass)#863 (2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(8) "my title"
  }
  [1]=>
  object(stdClass)#862 (2) {
    ["id"]=>
    int(3)
    ["title"]=>
    string(10) "my title 2"
  }
}

but I want to have only the result NOT the column name, like

[
  2,
  "my title"
],
[
  3,
  "my title 2"
]

yes, I can make it by looping the result and make new array without column name. But is there are any way to get the result in this fashion using Laravel ?


回答1:


Try

$recs = DB::table('table_name')->pluck('id', 'title');
dd($recs->all());



回答2:


You can use the map() and the array_values() methods:

$recs->map(function($i) {
    return array_values((array)$i);
})

I'm not sure about Laravel 4.2, but I've just tested it and it works perfectly in Laravel 5.3. If it doesn't work in 4.2, use the native array_map() function instead.




回答3:


Reference

Try $recs->flatten()->all()

Update

Since your $recs looks like an array from your error. Try converting to collection. I hope this will work on v4.2

$recsCollection = new \Illuminate\Database\Eloquent\Collection($recs);
$recsCollection->flatten()->all();



回答4:


DB::table('table_name')->all()->lists('id', 'title')->toArray()

Referance: Retrieving A List Of Column Values



来源:https://stackoverflow.com/questions/42978115/laravel-get-db-result-without-table-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!