【问题标题】:PHP foreach loop with w3 responsive grid带有 w3 响应式网格的 PHP foreach 循环
【发布时间】:2022-01-06 13:47:48
【问题描述】:

有没有一种方法可以使用 w3.css 和 foreach 循环创建多行三分之二,并使用示例数据库中的数据填充三分之二?

尝试使用,但这会在一行中创建三分之多:

<?php foreach ($products as $index => $product) :?>

    <div class="w3-row">
<?php foreach ($products as $index => $product) : ?>
      <div class="w3-third w3-container">
        <h2>product 1 </h2>
      </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endforeach; ?>

预期输出:

<div class="w3-row">
  <div class="w3-third w3-container">
    <h2>Item 1 from a database</h2>
  </div>
  <div class="w3-third w3-container">
    <h2>Item 2 from a database</h2>
  </div>
  <div class="w3-third w3-container">
    <h2>Item 3 from a database</h2>
  </div>
</div>

<div class="w3-row">
      <div class="w3-third w3-container">
        <h2>Item 4 from a database</h2>
      </div>
      <div class="w3-third w3-container">
        <h2>Item 5 from a database</h2>
      </div>
      <div class="w3-third w3-container">
        <h2>Item 6 from a database</h2>
      </div>
    </div>

【问题讨论】:

  • 请向我们展示您目前尝试过的 PHP。
  • 谢谢我更新了帖子,不确定它是否足够清楚我想要实现的目标

标签: php css loops foreach w3.css


【解决方案1】:

所以你想为循环的每三个元素获取一行。您可以通过使用模数检查其中有多少应该在一行中来实现这一点。

<?php foreach ($products as $index => $product): $aThird = ($index+1%3)===0; ?>
    <?php if ($aThird): ?>
        <div class="w3-row">
    <?php endif ?>
      <div class="w3-third w3-container">
        <h2>product 1 </h2>
      </div>
    <?php if ($aThird): ?>
        </div>
    <?php endif ?>
</div>
<?php endforeach; ?>

但我强烈建议查看网格布局https://css-tricks.com/snippets/css/complete-guide-grid/

【讨论】:

  • 对于真正的工作,最好将$aThird = ($index+1%3)===0; 更改为$aThird = ($index % 3) == 0;。因为数组索引从零开始,您需要为第一个 w3-third 添加&lt;div class="w3-row"&gt;
【解决方案2】:

您可以使用 array_chunk() 函数。它将一个数组拆分成新数组的块

$myArray = ['Item-1', 'Item-2', 'Item-3', 'Item-4', 'Item-5', 'Item-6'];

$myArray = array_chunk($myArray, 3);

foreach($myArray as $Array){

     echo '<div class="w3-row">';
     
     foreach($Array as $Value){
          echo '<div class="w3-third w3-container">'.$Value.'</div>';
     }

     echo '</div>';

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2014-09-12
    • 2017-05-12
    • 2019-11-11
    • 2015-05-06
    • 2016-09-26
    • 2012-07-19
    相关资源
    最近更新 更多