我如何在每个循环中动态更改数组的值?

时间:2018-09-08 03:32:40

标签: php arrays laravel

我将数据存储在数组中,因此我试图动态更改数组的值。例如,我在foreach循环中有$name[0]

我希望它在每个循环中自动为$name[1]$name[2]$name[3]。我正在使用laravel框架。

<tr>
 <td>Sn</td>
 <td>Name</td>
 <td>post</td>
 <td>Address</td>
 <td>father</td>
 <td>Grandfather</td>
 <td>Ctz no</td>
 <td>Contact</td>
</tr>
<?php $i = 1 ?>
@foreach($officials as $official)
<tr>
 <td>$i++</td>
 <td>{{$name[0]}}</td>
 <td>{{$post[0]}}</td>
 <td>{{$address[0]}}</td>
 <td>{{$father[0]}}</td>
 <td>{{$grandfather[0]}}</td>
 <td>{{$ctz[0]}}</td>
 <td>{{$contact[0]}}</td>
</tr>
@endforeach

2 个答案:

答案 0 :(得分:1)

您可以在进行foreach时保留变量的增量值

            <tr>
             <td>Sn</td>
             <td>Name</td>
             <td>post</td>
             <td>Address</td>
             <td>father</td>
             <td>Grandfather</td>
             <td>Ctz no</td>
             <td>Contact</td>
           </tr>
           @php 
            $i = 0;
           @endphp
           @foreach($officials as $official)
           <tr>
             <td>@php echo $i; @endphp</td>
             <td>@php echo $name[$i]; @endphp</td>
             <td>@php echo $post[$i]; @endphp</td>
             <td>@php echo $address[$i]; @endphp</td>
             <td>@php echo $father[$i]; @endphp</td>
             <td>@php echo $grandfather[$i]; @endphp</td>
             <td>@php echo $ctz[$i]; @endphp</td>
             <td>@php echo $contact[$i]; @endphp</td>
           </tr>
           @php
             $i++;
           @endphp
           @endforeach

这将起作用,但似乎很简单,您可以定义一个自定义的刀片指令,以在Laravel的AppServiceProviders中实现自己的规则。官方文档为here

答案 1 :(得分:0)

请尝试这个

@foreach($officials as $official)
               <tr>
                 <td>$loop->iteration</td>
                 <td>{{$official['name']}}</td>
                 <td>{{$official['post']}}</td>
                 <td>{{$official['address']}}</td>
                 <td>{{$official['father']}}</td>
                 <td>{{$official['grandfather']}}</td>
                 <td>{{$official['ctz']}}</td>
                 <td>{{$official['contact']}}</td>
               </tr>
               @endforeach