2017-06-24 9 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

関連する問題