<?php
$fatturati = ['2016'=>array_fill_keys(range(1,12),0),
                   '2017'=>array_fill_keys(range(1,12),0),
                   '2018'=>array_fill_keys(range(1,12),0),
                   '2019'=>array_fill_keys(range(1,12),0),
                   '2020'=>array_fill_keys(range(1,12),0),
                  
 ];
$query =
"SELECT
DATE_FORMAT(data, \"%c-%Y\") as meseanno
, SUM(totale) as totalemese
FROM `commesse`
WHERE YEAR(data) BETWEEN 2016 AND 2020
GROUP BY meseanno UNION SELECT
DATE_FORMAT(data, \"13-%Y\") as meseanno
, SUM(totale) as totalemese
FROM `commesse`
WHERE YEAR(data) BETWEEN 2016 AND 2020
GROUP BY meseanno";
$result = $mysqli->query($query);
while($data = mysqli_fetch_assoc($result)){
    $d = explode('-', $data['meseanno']); // in $d[0] ho il mese, in $d[1] l'anno;
    $fatturati[$d[1]][$d[0]] = $data['totalemese'];
}
// CREO UN ARRAY DI MESI
$mesi = [1=>'Gennaio', 2=>'Febbraio', 3=>'Marzo', 4=>'Aprile', 5=>'Maggio', 6=>'Giugno', 7=>'Luglio', 8=>'Agosto', 9=>'Settembre', 10=>'Ottobre', 11=>'Novembre', 12=>'Dicembre', 13=>'Totale'];
?>
<table class='table table-striped > fatturato'>
  <thead>
    <tr>
      <th scope='col'></th>
      <th class='intestazione_fatturato' scope='col'>
        Incasso<br>
        2016
      </th>
      <th class='intestazione_fatturato' scope='col'>
        Incasso<br>
        2017
      </th>
      <th class='intestazione_fatturato' scope='col'>
        Incasso<br>
        2018
      </th>
      <th class='intestazione_fatturato' scope='col'>
        Incasso<br>
        2019
      </th>
      <th class='intestazione_fatturato' scope='col'>
        Incasso<br>
        2020
      </th>
    </tr>
  </thead>
  <tbody>
  <?php
    $euro = "€";
    $anni = array_keys($fatturati);
    for($i=1; $i<=13;$i++){
        $tr = "<tr>";
        if ($i == 13) {
            $tr = '<tr style="color:yellow; background-color:black; font-weight: bold; text-align:left;">';
        }
        echo $tr.'<td>'.$mesi[$i].'</td>';
        foreach($anni as $anno)
        {
          echo '<td>'.$euro.' '.$fatturati[$anno][$i].'</td>';
        }
        echo "</tr>";
          }
  ?>
</tbody>
</table>