从JSON获取正确的集合格式
目前,我从Guzzle获得了一个JSON反馈,我将其转换为集合,以便通过Blade在@foreach中使用。 问题是我没有得到想要的收款单 在my@foreach中,我希望能够使用Laravel的默认标记:从JSON获取正确的集合格式,json,laravel,collections,Json,Laravel,Collections,目前,我从Guzzle获得了一个JSON反馈,我将其转换为集合,以便通过Blade在@foreach中使用。 问题是我没有得到想要的收款单 在my@foreach中,我希望能够使用Laravel的默认标记: @foreach($hostgroups作为$hostgroup) {{$hostgroup->name} @endforeach 以下是我目前的收藏: Collection {#215 ▼ #items: array:2 [▼ "result" => array:2 [
@foreach($hostgroups作为$hostgroup)
{{$hostgroup->name}
@endforeach
以下是我目前的收藏:
Collection {#215 ▼
#items: array:2 [▼
"result" => array:2 [▼
"Clearcase" => array:1 [▼
"alias" => "clearcase"
]
"FPGA" => array:1 [▼
"alias" => "fpga"
]
]
"result_code" => 0
]
}
我的型号
首先,您只能收集结果:
returncollect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
然后您可以更改迭代的方式:
@foreach($name=>$value的主机组)
{{$name}
@endforeach
更新:顺便说一句,如果您想要所要求的格式,您可以使用集合
上的map()
函数,如下所示:
$hostgroups=collect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
返回$hostgroups->map(函数($item,$key){
$i=[];
$i['name']=$key;
$i['alias']=$item['alias'];
返回$i;
});
或者,如果您想要stdClass
对象的集合
,那么您可以访问示例中的元素{{{$hostgroup->name}
:
$hostgroups=collect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
返回$hostgroups->map(函数($item,$key){
$i=新的stdClass();
$i->name=$key;
$i->alias=$item['alias'];
返回$i;
});
首先,您只能收集结果:
returncollect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
然后您可以更改迭代的方式:
@foreach($name=>$value的主机组)
{{$name}
@endforeach
更新:顺便说一句,如果您想要所要求的格式,您可以使用集合
上的map()
函数,如下所示:
$hostgroups=collect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
返回$hostgroups->map(函数($item,$key){
$i=[];
$i['name']=$key;
$i['alias']=$item['alias'];
返回$i;
});
或者,如果您想要stdClass
对象的集合
,那么您可以访问示例中的元素{{{$hostgroup->name}
:
$hostgroups=collect(json_decode($hostgroups->getBody()->getContents(),true)['result']);
返回$hostgroups->map(函数($item,$key){
$i=新的stdClass();
$i->name=$key;
$i->alias=$item['alias'];
返回$i;
});
Collection {#215 ▼
#0 => array:2 [▼
"name" => "Clearcase",
"alias" => "clearcase"
]
#1 = > array:2 [▼
"name" => "fpga",
"alias" => "fpga"
]
]
]
}