【问题标题】:php - Foreach - Wrapping <li> </li> with two results inside, then repeating.php - Foreach - 用两个结果包装 <li> </li>,然后重复。
【发布时间】:2011-08-24 21:48:39
【问题描述】:

使用 php - 我试图在数组上运行“foreach”,但我想将每两个结果包装在 li 标签中。输出将如下所示。

&lt;li&gt;

&lt;div&gt;result 1&lt;/div&gt;

&lt;div&gt;result 2&lt;/div&gt;

&lt;/li&gt;

&lt;li&gt;

&lt;div&gt;result 3&lt;/div&gt;

&lt;div&gt;result 4&lt;/div&gt;

&lt;/li&gt;

&lt;li&gt;

&lt;div&gt;result 5&lt;/div&gt;

&lt;div&gt;result 6&lt;/div&gt;

&lt;/li&gt;

我该怎么做呢?

谢谢!

【问题讨论】:

    标签: php arrays foreach counter html-lists


    【解决方案1】:
    $chunks = array_chunk($arr, 2);
    foreach ($chunks as $chunk) {
        // $chunk could have either 2 elements, or just one on the last iteration on an array with odd number of elements
        echo '<li>';
        foreach ($chunk as $value) {
            echo '<div>' . $value . '</div>';
        }
        echo '</li>';
    }
    

    【讨论】:

      【解决方案2】:
      $results = array(1, 2, 3, 4, 5, 6);
      echo "<li>";
      foreach($results as $pos => $result) {
          if ($pos > 2 && $pos % 2 == 0) {
              echo "</li>\n<li>";
          }
          echo "<div>result $result</div>";
      }
      echo "</li>";
      

      或更简单地说:

      $results = array(1, 2, 3, 4, 5, 6);
      $max = count($results);
      for($i = 0; $i < $max; $i++) {
          echo "<li>";
          echo "<div>result " . $results[$i] . "</div>";
          $i++;
          echo "<div>result " . $results[$i] . "</div>";
          echo "</li>";
      }
      

      【讨论】:

      • 这将与其他一些帖子存在相同的问题,您需要检查有效值以防有奇数#元素,如果它是最后一个(也是奇数)一个,关闭html标签。
      【解决方案3】:
      $count = 0;
      foreach ($array as $key=>$value) {
          ++$count;
          if ($count == 1) {
              echo "<li>";
              echo "<div>" . $value."</div>";    
          } else {
              echo "<div>" . $value."</div>";    
              echo "</li>";
              $count = 0;
          }
      }
      

      【讨论】:

      • 您在计数时缺少“$”符号,这将导致奇数计数时未闭合的 li。
      • 实际上,这是两个不同的问题:p
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2012-02-14
      • 2011-12-22
      相关资源
      最近更新 更多