Store query in array

2

Very good to everyone. I need to solve something that I can not give with it. I have a mysql query where I extract the income totals for each month of the year 2018.

$sql_g=mysqli_query($con, "SELECT MONTH(fecha_factura) AS mes, SUM(total_venta) AS total_mes 
FROM facturas,clientes 
WHERE facturas.id_cliente=clientes.id_cliente AND estado_factura=2 AND YEAR(fecha_factura) = 2018 
GROUP BY MONTH(fecha_factura)");

Then I execute a While to store the data in an array where [0] will be "January", and so on consecutively.

while ($row_g = mysqli_fetch_array($sql_g)) {

 $meses[] = $row_g['total_mes'];
}

e

In my case, I only have income during the months of April and March. For what it returns to me: Array ([0] => 513 [1] => 22.8) That is correct, in April they are 513 and on March 22.8.

The question is how could I make the months that there is no income be stored in the array with the amount of "0"? I am aware that the query will only return the values of the months in which there has been income, but is there any way to create an array with the structure of 12 months and if there is no income put the "0"?

I need this to put it on a graph.

Thank you very much.

    
asked by Jok 05.05.2018 в 18:58
source

1 answer

3

Generate the array of 0, at the beginning and then add the months you already have to the corresponding positions.

We can generate an empty array using a for , example:

for ($i = 0; $i < 12; $i++) {
    $meses[] = 0;
}

Or we can also generate an empty array using array_fill , example

$meses = array_fill(0, 12, null);

And then, we add only the months that we know exist:

while ($row_g = mysqli_fetch_array($sql_g)) {
    $meses[$row_g['mes']-1] = $row_g['total_mes'];
}

The rest is 1 per month, because the array is indexed at 0.

    
answered by 05.05.2018 / 19:12
source