如何在 Laravel 中将数组数组的集合转换为 Eloquent 风格的对象对象集合

时间:2021-06-23 18:55:54

标签: php arrays laravel object collections

我从 Airtable 中提取数据,返回如下:

Illuminate\Support\Collection {#496 ▼
  #items: array:11 [▼
    0 => array:3 [▼
      "id" => "rec4CaAx5EwGGi0I3"
      "fields" => array:8 [▼
        "description" => "Soft covers for switches"
        "price" => 7
        "tags" => array:2 [▼
          0 => "recvPyxXM6GdIjgEr"
          1 => "recvskfZPFMRPXzEb"
        ]

我可以找到如何转换为:

数组对象的集合,甚至

Collections of Collections 使用递归方法,

但不是

Objects of Objects (of Objects) 的集合

这样我就可以像使用普通的 Eloquent 获取的结果一样访问 $data->fields->name 之类的数据

1 个答案:

答案 0 :(得分:1)

原来我可以使用json编码/解码将其全部转换为对象然后收集它@

    $things = Airtable::table('things')->all();

    $things = json_decode(json_encode($things),FALSE);
    
    $things = collect($things);