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