【问题标题】:Laravel Foreach LoopingLaravel Foreach 循环
【发布时间】:2018-06-25 03:25:40
【问题描述】:

我需要显示迭代数组之前的值,这里是代码

<tr>
    <th></th>
    <th>Customer ID</th>
    <th>Customer Name</th>
    <th>Delivery Address</th>
    <th>Contact No.</th>
    <th>Zip Code</th>
    <th>Payment Terms</th>
    <th>Credit Limit</th>
</tr>
<?php $previousValue = null; ?>
@foreach($customer_count as $key => $value)
    <tr>
        <td>{{$previousValue=$value->customer_name }}</td>
        <td>{{ $value->id }}</td>
        <td>{{ $value->customer_name }}</td>
        <td>{{ $value->delivery_address }}</td>
        <td>{{ $value->contact_number }}</td>
        <td>{{ $value->area_id }}</td>
        <td>{{ $value->payment_term_id }}</td>
        <td>{{ $value->credit_limit }}</td>
    </tr>
@endforeach

我需要在迭代中显示以前的客户名称吗? 关于如何做到这一点的任何想法?

【问题讨论】:

    标签: laravel foreach iteration laravel-5.6


    【解决方案1】:

    最后设置值,我先设置空白

     @foreach($customer_count as $key => $value)
          <tr>
               <td>{{$previousValue or ""}}</td>
               .....
               .....
          </tr>
          <?php $previousValue = $value->customer_name ?>
      @endforeach
    

    【讨论】:

    • 这项工作感谢队友!!!特别是“或”部分非常有帮助!欢呼
    【解决方案2】:

    $customer_count[$key - 1]

    当然,您需要检查它是否存在或使用 null-coalesce 运算符或其他东西,所以:

    @php
    
    $previous = $customer_count[$key - 1] ?? false;
    
    @endphp
    

    然后使用:

    @if( $previous ) 
    ... some stuff ...
    @endif
    

    你需要注射的地方。

    【讨论】:

    • 已经试过这个但是未定义偏移量:-1(查看:C:\xampp\htdocs\fdis-laravel\resources\views\report\customer-count-group-detail.blade.php)
    • 是的,这就是我说使用 null-coalesce 运算符的原因。看看我编辑的答案。
    【解决方案3】:

    请试试这个

    <td>{{ (!$loop->first) ? $customer_count[$key - 1]->customer_name : '' }}</td>
    

    您可以阅读有关 foreach 循环的更多信息here

    【讨论】:

      【解决方案4】:

      首先将前一个值设置为空白,然后在$previousValue 中设置底部值

      <?php $previousValue = '';?>
      @foreach($customer_count as $key => $value)
          <tr>
              <td>{{ $previousValue }}</td>
              <td>{{ $value->id }}</td>
              <td>{{ $value->customer_name }}</td>
              <td>{{ $value->delivery_address }}</td>
              <td>{{ $value->contact_number }}</td>
              <td>{{ $value->area_id }}</td>
              <td>{{ $value->payment_term_id }}</td>
              <td>{{ $value->credit_limit }}</td>
          </tr>
          <?php $previousValue = $value->customer_name; ?>
      @endforeach
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-18
        • 2018-04-04
        • 2016-06-24
        • 2016-09-08
        • 2020-03-17
        • 2017-11-13
        • 2015-02-20
        • 1970-01-01
        相关资源
        最近更新 更多