简体   繁体   English

Laravel 如何在blade中显示数组的键值

[英]Laravel how to display the key values of array in blade

In my laravel -application, I create an array like this:在我的laravel ,我创建了一个这样的数组:

$positions = Position::whereHas('jobs')
    ->with('jobs')
    ->get()
    ->groupBy('name')
    ->mapSpread(function ($position) {
         return $position->jobs->where('job_status_id', '=', '2')->pluck('industry');
     })

this returns an array, which looks like this: (I've made a dd($positions))这将返回一个数组,如下所示:(我做了一个 dd($positions))

Illuminate\Support\Collection {#1280 ▼
#items: array:9 [▼
  "Engineer" => Illuminate\Support\Collection {#1279 ▶}
  "Analyst" => Illuminate\Support\Collection {#1274 ▼
     #items: array:1 [▼
       0 => App\Industry {#1294 ▶}
     ]
   }
  "Receptionist" => Illuminate\Support\Collection {#1304 ▶}
  "Programmer" => Illuminate\Support\Collection {#1306 ▼
     #items: array:2 [▶]
   }
  ]
}

Now, I want to display the key values and the amount of jobs the key value has in my blade view - for example "Programmer (2)"现在,我想在我的blade视图中显示键值和键值具有的作业数量 - 例如“程序员(2)”

I tried to do this:我试图这样做:

@foreach($positions as $k => $v)

  @foreach ($v as $key => $value)
        {{ $value->name }}
  @endforeach

@endforeach

but this only returns the name of the industry, like for example "IT" or "Construction" (which I get from the Industry relation)但这仅返回行业名称,例如“IT”或“建筑”(我从行业关系中获得)

So how can I achieve that?那么我怎样才能做到这一点呢?

You try count() method for a collection您尝试使用 count() 方法进行集合

@foreach($positions as $k => $v)
 <div>{{ $k }} ({{ $v->count() }})</div>
@endforeach

Reference: https://laravel.com/docs/6.x/collections#method-count参考: https : //laravel.com/docs/6.x/collections#method-count

Count the element in the for loop and display it like this in the view计算for循环中的元素并在视图中像这样显示

@foreach($positions as $k => $v)

  @foreach ($v as $key => $value)
        {{ $value->name }} {{ count($value->toArray()) }}
  @endforeach

@endforeach

Remove the toArray() if it gives error.如果出现错误,请删除toArray()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM