【问题标题】:Laravel check if related children not emptyLaravel 检查相关子项是否为空
【发布时间】:2015-02-18 23:05:47
【问题描述】:

我有一个收藏品,我要按照这个思路返回

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:已填写 字段2:填写

第 2 组


如何在编写标题之前检查每个 $group's->fields[]->contents 是否为 !empty?

抱歉任何错别字,已经非常非常晚了

编辑

我认为我需要按照以下方式做一些事情:

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

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

【问题讨论】:

  • 什么是contents,你能举个例子吗?

标签: php laravel collections


【解决方案1】:

试试这个,

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

【讨论】:

  • 嗯,它不起作用,因为$field 不是一个对象,而是一个对象数组 ($fields)... 对象数组,带有对象数组:/我几乎需要做if( ! $fields->sum('contents[0].value') )
【解决方案2】:

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

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

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

        unset( $form[$key] );

    }

}

那么你当然得更新你的查看代码

@foreach($form['groups'] as $group)...

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 2013-12-23
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2014-07-17
    • 2015-02-13
    相关资源
    最近更新 更多