Laravel通过使用多个对象嵌套foreach

时间:2018-04-10 04:40:13

标签: php arrays laravel foreach

我想在配置文件页面中使用一些数据,我已成功将这些数据传递给视图

    return view('pages.profile' , compact('data' , 'faculty' , 'scores' , 'sub' , 'finance_r'));

但是当我想使用嵌套的每一个将“sub”数据打印到foreach基础的“data”部分时,我收到了一个错误

Trying to get property 'id' of non-object (View: 

我想做的最简单的事情

@foreach ($data as $data)
  @foreach ($sub as $sub)
    {{ $sub->id }}
  @endforeach
@endforeach

我在laravel文档中找到了这个,但它不起作用

    @foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

我们如何才能在另一个foreach中使用foreach?

注意:我传递给视图的所有数据都是Object。 我的子数据是

Collection {#865 ▼
  #items: array:8 [▼
    0 => Subject {#856 ▼
      #table: "subject"
      +timestamps: false
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:5 [▼
        "id" => 8
        "name" => "پروگرامینگ"
        "number_of_credites" => 5
        "semester_id" => 1
        "faculty_id" => 2
      ]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
    1 => Subject {#857 ▶}
    2 => Subject {#858 ▶}

我的数据

    Collection {#848 ▼
  #items: array:3 [▼
    0 => Scores {#844 ▼
      #table: "scores"
      +timestampes: false
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [▼
        "id" => 4
        "subject_id" => 15
        "score" => 100
        "scores_student_details_id" => 7
        "created_at" => "2018-04-09 15:02:24"
        "updated_at" => "2018-04-09 15:02:21"

我实际上想根据"faculty_id" => 1

打印sub

1 个答案:

答案 0 :(得分:2)

您的问题是您在foreach循环中使用相同的名称。

您可以按照您的代码执行此操作,

@foreach ($data as $value)
  @foreach ($sub as $subValue)
    {{ $subValue->id }}
  @endforeach
@endforeach

但这不是好习惯,

根据我的观点,您必须在控制器中更改变量的名称, 就像你可以通过datas而不是datasubs代替sub

 return view('pages.profile' , compact('datas' , 'faculty' , 'scores' , 'subs' , 'finance_r'));

然后你可以做foreach循环,

@foreach ($datas as $data)
      @foreach ($subs as $sub)
        {{ $sub->id }}
      @endforeach
@endforeach
  

始终将变量名称与变量的作品相关联(单数/复数)。

如果您有任何疑问,请尝试并发表评论。