如何在循环和数组内部插入数据 [英] how to insert data while looping and inside array as well
问题描述
这是我的餐桌顺序:
+-------+-------+
| month | count |
+-------+-------+
| 6 | 11 |
| 11 | 27 |
| 12 | 9 |
+-------+-------+
我想使用融合图。假设年份是2017年,如何将缺少的月份放入正在使用的Fusioncharts数组中?我陷入了困境。
I want to create a graph using fusioncharts. Let's say that the year is 2017. How do I put the missing month into the array of which fusioncharts I'm using? I'm stuck on the condition.
这是我的代码:
$strQuery2 = "SELECT DATE_FORMAT(order_date, '%c') as month, COUNT(*) AS cnt FROM orders where YEAR(order_date)='2017' GROUP BY month ORDER BY `month` DESC";
$result2 = $dbhandle->query($strQuery2);
// Push the data into the array
while($row2 = $result2->fetch_assoc()) {
$q = $row2["month"];
$w = $row2["cnt"];
$e = 0;
$x = 1;
if ($x != $q){
echo "true";
array_push($arrData2["data"],
array(
"label" => $row2[$x],
"value" => $row2[$e]
)
);
}
else{
echo "false";
array_push($arrData2["data"],
array(
"label" => $row2["month"],
"value" => $row2["cnt"]
)
);
}
$x++;
echo $row2["month"] . "<br />";
echo $row2["cnt"] . "<br />";
}
推荐答案
不存在的数据库。如果将数据推送到空数组中:
You never get a month from the database that isn't there. If you push data into an empty array:
array_push($arrData2["data"]
最后您仍然得到一个仅包含从数据库返回的月份的数组。
you still end up with an array that only contains the months returned from the database.
您可以做的是首先创建一个所有12个月的数组:
What you can do is first create an array with all 12 months:
$arrData2["data"]=range(1,12,false);
您现在拥有一个包含12个元素(月)的数组1-12,所有值都为 false
(您可以使用任何值,数组或false(如果需要))
现在,在resultloop中,只需替换您具有以下值的数组元素:
You have now an array that contains 12 elements (months) from 1 - 12, all with values of false
. (You could use any value, an array or false if you need).
Now inside your resultloop, just replace the array elements you have values for:
$arrData2["data"][$row2["month"]] = array(
'label' => $row2["month"],
'value' => $row2["cnt"]
);
$ arrData2现在看起来像:
$arrData2 now will look like:
array(
1 => false,
2 => false,
3 => false,
4 => false,
5 => false,
6 => array('label'=> 6,'value'=> 11),
7 => false,
8 => false,
9 => false,
10 => false,
11 => array('label'=> 11,'value'=> 27),
12 => array('label'=> 12,'value'=> 9)
)
现在,您可以将所有 false
值替换为值 0
Now you can replace all the false
values for arrays with value 0
因此您的整个代码可以简化为:
So your whole code could be schortened to:
//set empty array
$arrData2['data'] = range(1, 12, false);
//fill elements we know
while($row2 = $result2->fetch_assoc()) {
$arrData2["data"][$row2["month"]] = array(
'label' => $row2["month"],
'value' => $row2["cnt"]
);
}
//replace the rest with 0
foreach($arrData2["data"] as $key => $value){
// skip what we already know
if($values !== false) continue;
// replace the rest
$arrData2["data"][$key]=array(
'label'=>$key,
'value'=> 0
);
}
echo print_r($arrData2,true);
这篇关于如何在循环和数组内部插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!