I have am using MySQL to generate data for a graph. The graph needs to include the months that have past during the current year. For Example: Today is July so the graph should include January-July. The SQL data does not have numbers for each month.
Here is my SQL Output:
Units_Counted Date
607 2
2120 5
42 7
The "date" field is the month. When I print it to the graph I need it to look like this.
Units_Counted Date
0 1
607 2
0 3
0 4
2120 5
0 6
42 7
Here is my current PHP code. I need to add another loop in here but I cant seem to get it right.
$Month = 1;
foreach ($stmtIndividualGraphDatarows as $stmtIndividualGraphDatarow){
if ($stmtIndividualGraphDatarow['GraphMonth'] == $Month)
{
echo "{";
echo "'x': '".$stmtIndividualGraphDatarow['GraphMonth']."',";
echo "'y':".$stmtIndividualGraphDatarow['GraphCounts'];
echo "},";
}
else {
echo "{";
echo "'x': '".$Month."',";
echo "'y': 0";
echo "},";}
$Month++;
}
Hope my code will be helpful:
<?php
$list = array(
array(
'GraphMonth' => 2,
'GraphCounts' => 607,
),
array(
'GraphMonth' => 5,
'GraphCounts' => 2120,
),
array(
'GraphMonth' => 7,
'GraphCounts' => 42,
),
);
$max = 0;
$month_count = array();
foreach ($list as $item)
{
$month = $item['GraphMonth'];
$count = $item['GraphCounts'];
if ($month > $max)
{
$max = $month;
}
$month_count[$month] = $count;
}
for ($i = 1; $i <= $max; $i++)
{
$month = $i;
$count = 0;
if (isset($month_count[$i]))
{
$count = $month_count[$i];
}
$msg = "{'x': '$month', 'y': '$count'}";
echo $msg, "
";
}
// output:
//{'x': '1', 'y': '0'}
//{'x': '2', 'y': '607'}
//{'x': '3', 'y': '0'}
//{'x': '4', 'y': '0'}
//{'x': '5', 'y': '2120'}
//{'x': '6', 'y': '0'}
//{'x': '7', 'y': '42'}