2017-06-24 56 views
0

我有一個代碼,將生成一個年份表,每個年份分成5年組。如何將每年的每個數據放在其各自的列中?把每年的數據放在5年組

這就是我到目前爲止。

$chunkSize = 5; 
    $starting_year = 2006; 
    $ending_year = date("Y"); 

    for($starting_year; $starting_year <= $ending_year; $starting_year++) { 
     $years[] = $starting_year; 
    } 

    for($i = 0; $i < count($years); $i+=5) 
    { 

     echo "<table class='table table-striped table-bordered'>"; 
     echo '<thead><tr>'; 
      echo '<th class="text-center">'.implode('<th class="text-center">', array_slice($years, $i, $chunkSize)).'</th>'; 
     echo '</tr></thead>'; 
      echo '<tr>'; 


    $result= $myDB->query("SELECT total FROM ".$myDB->prefix("statistics")." WHERE year='$years[$i]'") or die(mysql_error()); 
    $row = $myDB->fetchArray($result); 
     $total=$row['total']; 

     //echo "<td class='text-center'>".$total."</td>"; 
    echo '<th class="text-center">'.implode('<th class="text-center">', array_slice($total, $i, $chunkSize)).'</th>'; 


     echo '</tr>'; 



    } 
    echo "</table>"; 

電流輸出 enter image description here

期望的結果

2016 2017    
total total   
2011 2012 2013 2014 2015 
total total total total total 
2006 2007 2008 2009 2010 
total total total total total 

回答

1
<?php 
    $chunkSize = 5; 
    $starting_year = 2006; 
    $ending_year = date("Y"); 
    //create an array of years 
    $years = range($starting_year,$ending_year); 
    //[2006,2007,....,2016,2017] 

    //split years in required size 
    $chunked = array_chunk($years,$chunkSize); 
    //[ [2006,....,2010], [2011,...2015], [2016,2017]] 

    //reverse it 
    $reversed = array_reverse($chunked); 
    //[ [2016,2017], [2011,...2015], [2006,....,2010]] 

    echo "<table class='table table-striped table-bordered'><tbody>"; 
    foreach($reversed as $reverse) { 
    echo "<tr>"; 
    foreach($reverse as $year) { 
     echo "<th>{$year}</th>"; 
    } 
    echo "</tr><tr>"; 
    foreach($reverse as $year) { 
     $result= $myDB->query("SELECT total FROM ".$myDB->prefix("statistics")." WHERE year='{$year}'") or die(mysql_error()); 
     echo "<td>{$result['total']}</td>"; 
    } 
    echo "</tr>"; 
    } 
    echo "</tbody></table>"; 

的代碼可以優化更多,但這將做的工作。

+0

謝謝你的答案..工作很好..有一個愉快的一天 – blackrx