php 在 Laravel 刀片模板中分解字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34126520/
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
Explode string in laravel blade template
提问by saravanan mp
I'm new for laravel framework. I want to explode string and run foreach loop.
Here is my code, assume $data->facing="Hello,World";
我是 Laravel 框架的新手。我想分解字符串并运行 foreach 循环。这是我的代码,假设$data->facing="Hello,World";
@if ($data->facing != "")
@foreach($data->facings as $info)
<option>{{$info}}</option>
@endforeach
@endif
how to explode $data->facing
using ","
.
如何$data->facing
使用","
.
回答by Ben Rowe
Just simply explode, however this logic should come from your controller/model
只是简单地爆炸,但是这个逻辑应该来自你的控制器/模型
@if ($data->facings != "")
@foreach(explode(',', $data->facings) as $info)
<option>{{$info}}</option>
@endforeach
@endif
If $data
is some sort of model, I would suggest adding an accessor to your model
如果$data
是某种模型,我建议为您的模型添加一个访问器
class MyModel extends Model
{
public function getFacingsAttribute()
{
return explode(',', $this->facings);
}
}
Then you can simply treat it as an array, as per your original example.
然后你可以简单地把它当作一个数组,按照你原来的例子。
@foreach($data->facings as $info)
回答by Maha Dev
Use explode like this:
像这样使用爆炸:
$new_array = array();
if($data->facing) {
$new_array = explode(',',$data->facing);
}
@if (is_array($new_array) && count($new_array) > 0)
@foreach($new_array as $info)
<option>{{$info}}</option>
@endforeach
@endif
回答by tommy
Blades @foreach
directive is just a wrapper around PHPs native foreach
:
Blades@foreach
指令只是 PHP 原生的包装foreach
:
@foreach(explode(',', $data->facings) as $info)
<option>{{ $info }}</option>
@endforeach