将Laravel Collection转换为数组

时间:2016-02-03 12:53:01

标签: php laravel laravel-5

这是我的代码
$titles = DB::table('roles')->lists('title');
如何将 $ 标题 从Laravel 5集合转换为关联数组?

2 个答案:

答案 0 :(得分:4)

在函数中包含ID,并从Model:

调用
$titles = Role::lists('title', 'id')->toArray();

或者直接打电话:

$titles = DB::table('roles')->lists('title', 'id');

在这种情况下,例如,在选择字段中,id将是选项值。

答案 1 :(得分:2)

laravel集合具有toArray方法,该方法将返回数字键控的内容数组。 (索引将与集合中的索引完全相同。要重置它们,请先在集合上调用values。)

$titles = DB::table('roles')->lists('title');

$result = $titles->toArray();

对于关联数组,您需要使用类似的方法手动执行此操作。

$titles = DB::table('roles')->lists('title', 'id');

$result = [];

foreach($titles as $title) {
    // using an ID as the key and title as the value
    $result[$title->id] = $title->title;
}