【问题标题】:Laravel How to put data horizontally into Three columns with foreachLaravel如何使用foreach将数据水平放入三列
【发布时间】:2019-07-08 08:50:19
【问题描述】:

我正在使用 laravel-dompdf 创建 PDF 文件。我想使用 foreach 循环将数据水平放入三列。这并不容易。

$items = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'ffff', 'gggg', 'hhhh', 'iiii'];

<table style="width:100%">

@foreach($items as $key => $item)

  <tr>

  @if($key % 2 == 0)<td>{{ $item }}</td>@endif

  @if($key % 2 != 0)<td>{{ $item }}</td>@endif


  </tr>

@endforeach

</table>

【问题讨论】:

  • dd($couponcodes)的输出更新你的问题
  • 它只是一个数组。我会更新的。
  • 您的代码有什么问题?问题出在哪里?
  • 它无法正常工作。

标签: php laravel


【解决方案1】:

你可以用这个sn-p,

<table style="width:100%">
    @foreach($items as $key => $item)
        @if($key % 3 == 0) <!-- if index % 3 is 0 then create tr -->
        <tr>
        @endif
            <td>{{$item}}</td>
        @if(($key+1) % 3 == 0) <!-- if index + 1 % 3 is 0 then close tr -->
        </tr>
        @endif
    @endforeach
    @if(count($items) % 3 != 0)
        </tr>
    @endif
</table>

【讨论】:

  • 如果最后一个条件为假,您忘记在 foreach 之后关闭 tr 标记
【解决方案2】:

使用此代码:

@foreach($data as $key => $item)

    @if ($key % 3 == 0)
        <tr>
    @endif

    <td>{{ $item }}</td>

    @if (($key + 1) % 3 == 0)
        </tr>
    @endif

@endforeach

@if (($key + 1) % 3 != 0)
    </tr>
@endif

你必须:

  • &lt;tr&gt; 标记开头(或每 3 条记录)
  • 处理 3 条记录时关闭 &lt;tr&gt; 标签
  • 循环结束后必须检查最后一个&lt;tr&gt;标签是否已经关闭,否则关闭

【讨论】:

    【解决方案3】:

    试试这个

    <table style="width:100%">
        <?php $i = 0; ?>
        @foreach($items as $key => $item)
            @if($i == 2)
            <tr>
            @endif
                <td>{{$item}}</td>
            @if($i == 2)
                <?php $i = 0; ?> 
            </tr>
            @endif
           <?php $i++; ?>
        @endforeach
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2020-09-04
      • 2020-05-09
      • 2020-12-28
      • 1970-01-01
      相关资源
      最近更新 更多