我在Laravel集合上有一个循环内部循环,有时我需要从第二个循环集合中删除一些对象。这是代码
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
}
return $all_groups;
}
问题在于group-> templates的集合从简单(而不是assoc)数组变成对象。这是示例响应的样子
我正在尝试展平$ group-> templates-> flatten(),但在最终响应中,模板仍作为对象而不是数组。
此测试展平有效
...
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
return $group->templates->flatten()//This code works i get fluttened array
}
但是最终变量仍然返回对象而不是数组
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
$group->templates->flatten()//Use flatten here
}
return $all_groups;//Templates are returned not as an array but still as an object (Same variant as on attached image)
}
答案 0 :(得分:1)
使用values()
重置密钥,并使用setRelation()
替换关系:
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->setRelation('templates', $group->templates->forget($key)->values());
}
}
}
return $all_groups;
}
您也可以使用except()
代替forget()
:
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
$group->setRelation('templates', $group->templates->except($id));
}
return $all_groups;
}