【问题标题】:Appending the index to a variable name in a loop在循环中将索引附加到变量名
【发布时间】:2014-07-11 22:12:34
【问题描述】:

我在视图中使用 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 是我在控制器中构建并传递给刀片模板的对象。 $scores 中的数据如下所示:

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

【问题讨论】:

  • 这是可能的,但您几乎可以肯定是以错误的方式接近它。为什么$scores 不是数组?
  • 为什么不把洞做成数组,听起来很奇怪

标签: php laravel blade


【解决方案1】:

试试

<?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

【讨论】:

  • {{ $scoresArray["hole$i"] }} 也不起作用
  • 另外 $scores 中的数据来自数据库,所以我无法更改 t_holes 和 s_holes 的格式
  • 我自己试过,$scoresArray["hole$i"] 工作正常。如果数据来自数据库,那么您的设计是错误的。洞应该是分数的关系,而不是分数的属性。如果您正确定义了关系, s_holes 和 t_holes 都将成为 Illuminate\Database\Eloquent\Collection 的一个实例,它可以像数组一样迭代,我的回答仍然有效。有关数据库设计的更多信息,请查看 https://google.com/search?q=database+normalization
猜你喜欢
  • 2015-08-23
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
相关资源
最近更新 更多