php Laravel Blade 模板 @foreach 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34700499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:10:20  来源:igfitidea点击:

Laravel Blade Templating @foreach order

phplaravelforeachblade

提问by Ugo Guazelli

Is there any way to sort @foreachloop in laravel blade?

有没有办法对@foreachLaravel Blade 中的循环进行排序?

@foreach ($specialist as $key)
  <option value="{{$key->specialist_id}}"> {{$key->description}}</option>
@endforeach

I wolud like to order by $key->description,

我想订购$key->description

I know I can use order by in my controller,

我知道我可以在我的控制器中使用 order by,

->orderBy('description')

but the controller returns other values and those values must be sorted as well, so I need to order by in blade.

但控制器返回其他值,这些值也必须排序,所以我需要按刀片排序。

回答by Denis Mysenko

Assuming that your $specialist variable is an Eloquent collection, you can do:

假设你的 $specialist 变量是一个 Eloquent 集合,你可以这样做:

@foreach ($specialist->sortBy('description') as $oneSpecialist)
  <option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
@endforeach

Moreover, you could call your Eloquent model directly from the template:

此外,您可以直接从模板调用您的 Eloquent 模型:

@foreach (Specialist::all()->sortBy('description') as $oneSpecialist)
  <option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
@endforeach

Note that you are using a misleading variable name of $key in your foreach() loop. Your $key is actually an array item, not a key. I assume that you saw foreach ($array as $key => $value) syntax somewhere and then removed the $value?

请注意,您在 foreach() 循环中使用了误导性的 $key 变量名称。你的 $key 实际上是一个数组项,而不是一个键。我假设您在某处看到了 foreach ($array as $key => $value) 语法,然后删除了 $value?

回答by Derek Pollard

I would suggest using a laravel collection. More specifically, the sortBy(). You can use either of these in your view or the controller that you are passing the data from. If the data is being passed by a model, be sure to use the collect()function before proceeding to use any of the others listed.

我建议使用 laravel集合。更具体地说,sortBy(). 您可以在视图或从中传递数据的控制器中使用其中任何一个。如果数据由模型传递,请确保collect()在继续使用列出的任何其他函数之前使用该函数。

Hope this helps!

希望这可以帮助!