【问题标题】:How to convert multidimensional array to collections into Laravel如何将多维数组转换为集合到 Laravel
【发布时间】:2019-10-31 22:15:40
【问题描述】:

从 API 我得到一个多维数组的响应,例如:

如何将此数组转换为 eloquent 对象,以便我可以使用 $collection->Query->Country or $collection->Carriers->where('id',12345) ... 在视图中访问

我尝试:

$res1 = collect($res1)->map(function($row) {
    return collect($row);
});

dd($res1);

但没有成功!

我该如何解决这个问题?

【问题讨论】:

  • 写你的代码,不要放图片。

标签: php arrays laravel eloquent


【解决方案1】:

在这种情况下你可以使用

$collection['Carriers']->where('id',12345)
// or
collect($collection['Carriers'])->where('id',12345)

用于制作具有您可以使用的属性的新 Eloquent 模型

$query =  (new Query())->setRawAttributes($collection['Query']);

然后使用

$query->Country;

或者你可以用这种粗略的方式来做

$model = (new Model())->setRawAttributes($res1);

和你提到的用法

$model->Query->Country or $model->Carriers->where('id',12345)

【讨论】:

  • 我调用了数组上的成员函数 where()
  • 使用collect($collection['Carriers'])->where('id',12345)
猜你喜欢
  • 2019-07-05
  • 2018-12-31
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2016-05-12
  • 2018-05-03
  • 1970-01-01
相关资源
最近更新 更多