Laravel检查相关的孩子是否空着

时间:2015-02-18 23:05:48

标签: php laravel collections

我有一个我正在回归

的集合
form : {
    groups : [
         {
             title : 'group 1'
             fields : [
                 {
                     name: 'field 1',
                     contents:[
                         {
                             value: 'Filled in'
                         }
                     ]
                 }
                 {
                     name: 'field 2',
                     contents :[
                         {
                             value: 'Filled in'
                         }
                     ]
                 }
             ]
         },
         {
             title : 'group 2'
             fields : [
                 {
                     name: 'field 1',
                     contents:[]
                 }
                 {
                     name: 'field 2',
                     contents :[]
                 }
             ]
         }
     ]
 }

然后我会像这样循环

@foreach($form->groups as $group)
  {{ $group->title }}
  @foreach(group->fields as $field)
    {{ $field->name }} {{ $field->contents[0]->value }}
    ...

但是我处于空洞field.contents的情况下,但我仍在回应群组标题,例如上面会回应


第1组

第1栏:填写 第2栏:填写

第2组


如何在撰写标题之前检查每个$ group' s->字段[] - >内容是否为空?

对任何拼写错误道歉,这是非常非常晚的

修改

我想我需要做一些事情:

if( ! $group->fields->sum('contents[0].value') )

有没有办法可以将参数传递给sum函数?

2 个答案:

答案 0 :(得分:1)

试试这个,

@foreach($form->groups as $group)
  {{ $group->title }}
  @foreach(group->fields as $field)
    @if(!empty($field->contents))
    {{ $field->name }} {{ $field->contents[0]->value }}
    @endif
    ...

答案 1 :(得分:0)

在不知道所有细节的情况下,我可能会在将其传递给视图之前消除您不想要的元素。通过在集合上使用toArray()并运行:

foreach( $form as $key => $groups ){

    if( ! isset( $groups['fields']['contents'][0] ) ){

        unset( $form[$key] );

    }

}

当然,您必须更新视图代码

@foreach($form['groups'] as $group)...
相关问题