toArray()方法简介
toArray 方法将集合转换成 PHP 数组。如果集合的值是 Eloquent 模型,那也会被转换成数组:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
DB:table()->get();
的返回值怎么转换为数组?
方法一:
$objectData = DB::table('spaces')->get();
//返回的是 object(Illuminate\Support\Collection)
$arrayData = DB::table('spaces')->get()
->map(function ($value) {return (array)$value;})
->toArray();
//返回的是 array
方法二:
public function objectToArray($object) {
//先编码成json字符串,再解码成数组
return json_decode(json_encode($object), true);
}
DB:table()->first();
的返回值怎么转换成数组
使用get_object_vars()
get_object_vars — 返回由对象属性组成的关联数组;
DB::table('spaces')->first();
//返回值是 object(stdClass)
$arrayData = get_object_vars($objectData);
//返回值是array