Laravel - 将数组转换为 eloquent 集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54042847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - convert array into eloquent collection
提问by Aleks Per
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 版本
回答by Jacem Chaieb
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;
});
回答by behnam
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