我正在使用Laravel和Blade模板进行查看。我正在写出一些数据,因为我的专栏名称与末尾的数字相同,我认为我可以遍历它们而不是全部写出来。
以下是我目前的情况:
我正在传递一个名为$ scores的对象/数组:
<span>{{ $scores->hole1 }}</span>
<span>{{ $scores->hole2 }}</span>
<span>{{ $scores->hole3 }}</span>
<span>{{ $scores->hole4 }}</span>
<span>{{ $scores->hole5 }}</span>
.. 等
我想做的是:
@for ($i = 1; $i < 19; $i++)
<span>{{ $scores->hole . ${i} }}</span>
@endfor
但我似乎无法正确地将索引值附加到变量名称的末尾。这可能吗,或者我是以错误的方式接近这个?
$ scores是我在控制器中构建的对象并传递给刀片模板。 $ score中的数据如下所示:
object(stdClass)[212]
public 'id' => int 3
public 'course_name' => string 'Golf Club A' (length=15)
public 'played_date' => string '2014-02-05' (length=10)
public 's_hole1' => int 5
public 's_hole2' => int 6
public 's_hole3' => int 4
public 's_hole4' => int 5
public 's_hole5' => int 6
public 's_hole6' => int 4
public 's_hole7' => int 4
public 's_hole8' => int 5
public 's_hole9' => int 4
public 's_hole10' => int 3
public 's_hole11' => int 5
public 's_hole12' => int 4
public 's_hole13' => int 5
public 's_hole14' => int 4
public 's_hole15' => int 3
public 's_hole16' => int 4
public 's_hole17' => int 3
public 's_hole18' => int 4
public 't_hole1' => int 4
public 't_hole2' => int 3
public 't_hole3' => int 5
public 't_hole4' => int 4
public 't_hole5' => int 4
public 't_hole6' => int 4
public 't_hole7' => int 4
public 't_hole8' => int 5
public 't_hole9' => int 4
public 't_hole10' => int 3
public 't_hole11' => int 5
public 't_hole12' => int 4
public 't_hole13' => int 5
public 't_hole14' => int 4
public 't_hole15' => int 3
public 't_hole16' => int 4
public 't_hole17' => int 3
public 't_hole18' => int 4
答案 0 :(得分:0)
尝试
<?php $scoresArray = (array) $scores; ?>
@for ($i = 1; $i < 19; $i++)
<span>{{ $scoresArray["hole$i"] }}</span>
@endfor
顺便说一句,你的方法似乎错了。尝试使用数组存储空洞并使用@foreach
循环。对于未来的变化,这样的事情会更加灵活
// Create object
$scores = (object) array(
'id' => 3,
'course_name' => 'Golf Club A',
'played_date' => '2014-02-05',
's_holes' => array(5, 6, 4, 5, 6, 4, 4, 5, 4, 3, 5, 4, 5, 4, 3, 4, 3, 4),
't_holes' => array(4, 3, 5, 4, 4, 4, 4, 5, 4, 3, 5, 4, 5, 4, 3, 4, 3, 4)
);
// In your view
@foreach ($scores->s_holes as $hole => $value)
<span>Hole {{$hole}}: {{$value}}</span>
@endforeach