duanlian1320
duanlian1320
2014-06-29 16:19

以3列N行显示表中的数据

已采纳

I'm kinda stuck with this which might seem dumb at the moment.

I have a set of arrays which can have any number of elements can be from 6 to N

I can't modify the structure of the site right now, but it's made with a bootstrap responsive table. i need to display every element in the table but maximum 3 columns with N number of rows.

Like this

enter image description here

I did this in order to get the number of rows

$rows=ceil(count($array)/3);

Then i do a couple of for to display the table in that distribution

for( $i=0; $i<$rows; $i++ ) {
<tr>  
    for($j=0;$j<3;$j++){
      <td>Value</td>
    }
</tr>
}

Until here all fine, problem is i need to access to the array keys from 0 to N and i haven't figured out how

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douyu0792 douyu0792 7年前

    I managed to do it using array_key_exists and a counter.

    $key = 0;
    for( $i=0; $i<$rows; $i++ ) {
     <tr>  
        for($j=0;$j<3;$j++){
          if ( array_key_exists( $key, $array ) ) {
             <td>echo $array[$key]</td>  // if the index is in the array print the column
          }
        }
     </tr>
    }
    
    点赞 评论 复制链接分享
  • douguwo2275 douguwo2275 7年前

    Try like this:

    foreach($array as $val)) {
    
      echo '<div class="col-md-4">' . $val . '</div>';    
    
    }
    

    If your site "grid" has 12 cols, you can just use classes like col-sm-4, col-md-4 etc. to split your elements into 3 columns. Check the bootstrap manual for more info: http://getbootstrap.com/css/

    点赞 评论 复制链接分享
  • duanfen9983 duanfen9983 7年前

    Not tested but the logic is something like this:

    $i = 0;
    foreach ($array as $a)
    {
        if($i == 0 || $i % 3 == 0)
        {
            if ($i % 3 == 0)
            {
                echo "</tr>";
            }
            echo "<tr>";
        }
        echo "<td>" . $a . "</td>";
        $i++;
    }
    echo "</tr>";
    
    点赞 评论 复制链接分享

为你推荐