Laravel collection 报错 join(): Invalid arguments passed

混淆了 array 与 collection,join 并不支持 collection.laravel

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,那么git

  • toArray() 会把 model 也转换成对应的 array
  • all() 依然保留原 model

collection 在 laravel 中频繁使用

全部的 eloquent 查询返回都是一个 collection 实例,而不是 array。github

我更喜欢 collection 的缘由

  • toJson() 比 json_encode() 写起来更顺手,由于实例方法比方法中还要缀上源数据对象要容易记忆的多
  • collection 扩充了 array 的数据操做集,在数据处理上开发效率要高不少,这也是 Python 的优点

如何判断当前对象是 array 仍是 collection

laravel tinker 中测试json

$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/collectspa

相关文章
相关标签/搜索