在foreach循环中分别显示奇数和偶数数组数据

时间:2018-08-02 10:59:53

标签: php html laravel-4

<?php $ctr = 0; ?>
@foreach($level1['Weapons'] as $key => $header)
   @if($ctr% == 0) 
      <div class="left">
   @endif
   @if($ctr% == 1) 
      <div class="right">
   @endif
      <ul>
         <li>
            <span class="ability">{{$key}}</span><br>
            <p class="ability-desc">{{$header['desc']}}</p>
         </li>
       </ul>

       @if($ctr == 8 || $ctr == 7) 
         </div>
       @endif

       <?php $ctr++; ?>
@endforeach

数组:

 'level1' =>
    array (    
 'Weapons' =>
    array (
      'Misfortune' =>
      array (
        'desc' => 'You can make any person fall',
      ),
      'Sorrow' =>
      array (
        'desc' => 'You can make a person cry just by looking at them',
      ),
      'Stink' =>
      array (
        'desc' => 'No living person can endure your fart',
      ),
      'Harden' =>
      array (
        'desc' => 'You can make soft things hard, even water',
      ),

我有一个foreach,它将列出数组描述中的所有项目。我的问题是我创建了一个if语句,将ODD和EVEN数组元素中的值分配给div,这将根据结果将它们分为左右两边。我注意到结果似乎只显示在左侧。我该如何重新排列或做出if语句来满足我的想法。我希望这个问题有意义。

1 个答案:

答案 0 :(得分:1)

我会在循环中建立2个字符串,然后在循环后将它们回显。自从我做了php以来已经有一段时间了,所以可能会有一些语法错误,但是您应该了解一下总体思路:

<?php 
  $ctr = 0; 
  $leftLi = "";
  $rightLi = "";
  
  foreach($level1['Weapons'] as $key => $header)
  {
    if ($ctr % 2 == 0)
    {
        $leftLi += MakeLi($key, $header['desc']);
    } else {
        $rightLi += MakeLi($key, $header['desc']);
    }
    
    $ctr++;
  }
  
  function MakeLi($key, $headerText)
  {
      return "
    <li>
      <span class=\"ability\">" . $key . "</span><br>
      <p class=\"ability-desc\">" . $headerText . "</p>
    </li>";
  }
?>



<div class="left">
  <ul>
    <?php echo $leftLi; ?>
  </ul>
</div>

<div class="right">
  <ul>
    <?php echo $rightLi; ?>
  </ul>
</div>