Laravel - 获取没有表列名的数据库结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42978115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:38:54  来源:igfitidea点击:

Laravel - get DB result without table column name

laravellaravel-4.2

提问by user2609021

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

我希望结果只包含 Laravel 4.2 中不包含表列名的值。例如,

$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 ?

是的,我可以通过循环结果并创建没有列名的新数组来实现。但是有没有办法使用 Laravel 以这种方式获得结果?

回答by EddyTheDove

Try

尝试

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

回答by Alexey Mezenin

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

您可以使用map()array_values()方法:

$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.

我不确定 Laravel 4.2,但我刚刚测试过它,它在 Laravel 5.3 中完美运行。如果它在 4.2 中不起作用,请改用本机array_map()函数。

回答by Saumini Navaratnam

Reference

参考

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

尝试 $recs->flatten()->all()

Update

更新

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

由于您$recs的错误看起来像一个数组。尝试转换为collection. 我希望这将适用于 v4.2

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

回答by Preshan Pradeepa

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

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

Referance: Retrieving A List Of Column Values

参考:检索列值列表