如何将值写入html表中的正确月份?
对不起,我英语不好。

$mesi = array("January", "February", "March", "April", "May", "June",
               "July", "August", "September", "October", "November", "December");

$array = $class->startEndDate('12'); // chiave arrays
echo '<table class="table table-bordered">';
echo '<thead>';
echo '<th class="text-center">Country</th>';
foreach ($mesi as $mese) {
    echo '<th class="text-center">' . $mese . '</th>';
}
echo '</thead>';
echo '<tbody>';
echo '<tr>';
$query = "SELECT * FROM countries";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    echo '<td class = "text-center">' . $row['country_name'] . '</td>';

    $sql = "select sum(quantity), country_id,
                   concat(year(date), '_', month(date)) as meseAnno
            from subscription
            where country_id = " . $row['country_id'] .
            " group by meseAnno";

    $res = mysql_query($sql);
    while ($rows = mysql_fetch_assoc($res)) {
        //the code here!
    }
    echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>

在第二个查询中,我检索id country\u id为的国家的订阅。
第二次查询结果:
php - 将值写入正确的月份-LMLPHP
第一行的列meseAnno表示2015_4,所以是四月,但值7是在一月插入的。为什么?
提前谢谢。
php - 将值写入正确的月份-LMLPHP

最佳答案

问题是月数是12,但查询结果的行数可以少于12。
您可以更改SQL查询以获得一致的结果,或者在不修改查询的情况下,尝试以下操作:

(...)
$res = mysql_query( $sql );

$tableLine = array_fill( 1, 12, '<td>&nbsp;</td>' );
while( $row = mysql_fetch_assoc( $res ) )
{
    $month = preg_replace( '/^\d+_(\d+)$/', '\1', $row['meseAnno'] );
    $tableLine[ $month ] = "<td>{ YOUR MONTH VALUE HERE }</td>";
}
echo implode( '', $tableLine );

echo '</tr>';
(...)

首先,用12个空的<td>填充数组,然后在while()循环中-仅替换匹配的月份。
最后,你回显内爆数组。

10-05 21:25
查看更多