[英]Laravel - convert array into eloquent collection
I need to use data from an API.我需要使用来自 API 的数据。
I create a function:我创建了一个函数:
public function getItems()
{
$client = new \GuzzleHttp\Client();
$res = $client->get('https://app.example.com/api/getItems');
$vouchers = json_decode($res->getBody(), true);
dd($vouchers);
return view('api', compact('vouchers'));
}
and dd($vouchers)
return me:和
dd($vouchers)
返回给我:
Now when I try to use $vouchers array with blade engine like:现在,当我尝试将 $vouchers 数组与刀片引擎一起使用时,例如:
<body>
@foreach ($vouchers as $v)
<p>{{$v->name}}</p>
@endforeach
</body>
I got error:我有错误:
"Trying to get property 'name' of non-object (View: .... etc...
How I can convert array into eloquent collection.我如何将数组转换为雄辩的集合。 I use the latest Laravel 5.7 version
我用的是最新的 Laravel 5.7 版本
Actually your $vouchers
is an array of arrays, 实际上,您的
$vouchers
是一个数组数组,
So you may want to convert your sub-arrays to objects: 因此,您可能需要将子数组转换为对象:
You can do it simply using: 您可以使用以下方法简单地做到这一点:
foreach ($vouchers['vouchers'] as $key => $value) {
$vouchers['vouchers'][$key] = (object) $value;
}
.. or using collections: ..或使用集合:
$vouchers = collect($vouchers['vouchers'])->map(function ($voucher) {
return (object) $voucher;
});
This is because arrays have index. 这是因为数组具有索引。 you can do something like this :
您可以执行以下操作:
@for ($i = 0; $i < count($vouchers); $i++)
<p>{{$vouchers[$i]->name}}</p>
@endfor
Update 更新资料
If each of them included another array, you can try this instead : 如果它们每个都包含另一个数组,则可以尝试以下方法:
@for ($i = 0; $i < count($vouchers); $i++)
<p>{{$vouchers[$i][0]->name}}</p>
@endfor
要将数组转换为Illuminate\\Database\\Eloquent\\Collection
您可以将hydrate()
方法与目标Eloquent 模型一起使用,例如:
$eloquentCollection = TheEloquentModel::hydrate($arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.