PHP将空月插入foreach循环
我正在使用MySQL为图形生成数据。图表需要包括本年度过去的月份。例如:今天是七月,所以图表应该包括一月到七月。SQL数据没有每个月的编号 以下是我的SQL输出:PHP将空月插入foreach循环,php,graph,foreach,Php,Graph,Foreach,我正在使用MySQL为图形生成数据。图表需要包括本年度过去的月份。例如:今天是七月,所以图表应该包括一月到七月。SQL数据没有每个月的编号 以下是我的SQL输出: Units_Counted Date 607 2 2120 5 42 7 “日期”字段是月份。 当我把它打印到图表上时,我需要它看起来像这样。 Units_Counted
Units_Counted Date
607 2
2120 5
42 7
“日期”字段是月份。
当我把它打印到图表上时,我需要它看起来像这样。Units_Counted Date
0 1
607 2
0 3
0 4
2120 5
0 6
42 7
这是我当前的PHP代码。我需要在这里添加另一个循环,但我似乎不能得到它的权利
$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++;
}
希望我的代码对您有所帮助:
<?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, "\n";
}
// 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'}
我已经将数据存储在数组中。有没有一种方法可以把它结合起来,而不是把它全部拉出来再做一次?你是说像你那样做的?