Guys这是mysql表的输出。它表明month(Value)
得到特定疾病的count(Total)
。现在我有一个12个月的php array()
,我想与该数组进行比较,发现如果特定月份没有从表中返回的数据,则在其他12个月新的array()
中添加该月份的0
,或者从表中找到的值。
Value | dname | Total
5 | Root Canal | 1
8 | Root Canal | 1
我在php中的代码
foreach($ResultArray2[1] as $key => $val){
if(empty($row_d['Value'])){
$ResultArray2[$i][$key] = '0';
else
$ResultArray2[$i][$row_d['Value']] = $row_d['Total'];
这就是我得到的
Array ( [1] => Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 ) [2] => Array ( [5] => 1 [8] => 1 )
)
这就是我需要的阵列(
[1] => Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 ) [2] => Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 1 [6] => 0 [7] => 0 [8] => 1 [9] => 0 [10] => 0 [11] => 0 [12] => 0 )
)
如果我理解你的问题是正确的,那么
$finalResult = array();
while($row = mysql_fetch_object($querResult)) {
if(!is_array($finalResult[$row->dname]) {
$finalResult[$row->dname] = array_pad(array(), 13, 0);
}
$finalResult[$row->dname][$row->Value] = $row->Total;
}
基本上,代码检查是否已经存在针对特定疾病的数组。如果不是,它会创建一个大小为13的数组[忽略0],填充值为0,并在移动中更新值。这里疾病成了外阵的关键。如果你愿意,你可以使用从疾病名称到整数ID的映射。在这种情况下,
$finalResult[$map[$row->dname]][$row->value] = $row->Total;
$counts = array_fill(1,12,0);
while ($row = mysql_fetch_assoc($res)){
$counts[$row['Value']] = $row['Total'];
}
编辑:因为你似乎想得到所有的疾病,所以把整个事情作为一个查询可能更容易,比如:
SELECT name,
SUM(IF(Value=1,1,0) as month1,
SUM(IF(Value=2,1,0) as month2,
SUM(IF(Value=3,1,0) as month3,
...
FROM tablename
GROUP BY name