混淆了 array 與 collection,join 並不支持 collection.
array 與 collection 不同的 join 實現
- collect([1, 2, 3, 4, 5])->implode('-');
- join('-', [1, 2, 3, 4]);
將 array 轉換成 collection
$collection = collect([1, 2, 3]);
將 collection 轉換成 array
$collection->toArray();
all() 與 toArray() 的區別
如果 collection 中的 item 是 model,那么
- toArray() 會把 model 也轉換成對應的 array
- all() 依然保留原 model
collection 在 laravel 中頻繁使用
所有的 eloquent 查詢返回都是一個 collection 實例,而不是 array。
我更喜歡 collection 的原因
- toJson() 比 json_encode() 寫起來更順手,因為實例方法比方法中還要綴上源數據對象要容易記憶的多
- collection 擴充了 array 的數據操作集,在數據處理上開發效率要高很多,這也是 Python 的優勢
如何判斷當前對象是 array 還是 collection
laravel tinker 中測試
$a = collect([1, 2, 3])->all() >>> gettype($a) => "array" >>> $c = collect([1, 2, 3]) >>> gettype($c) => "object" >>> get_class($c) => "Illuminate\Support\Collection" >>> get_class($a) PHP Warning: get_class() expects parameter 1 to be object, array given on line 1
可見,gettype 可以判斷是否是 array,但是 gettype 無法直接得知具體的 object 對應的 class,需要調用 get_class。
如何在 laravel 項目之外使用 collection
https://github.com/tightenco/collect