简体   繁体   English

通过将其与MySQL数据进行比较来填充PHP数组

[英]Fill PHP Array by comparing it with MySQL data

Guys this is mysql tables output. 伙计们,这是mysql表的输出。 It show for month(Value) get count(Total) for a particular disease. 它显示特定疾病的month(Value)获得count(Total) Now I have a php array() of 12 months and I want to compare with that array and find that if for particular month their is no data returned from table add 0 for that month in other new array() of 12 months or else the value found from table. 现在我有一个12个月的php array() ,我想与该数组进行比较,发现如果特定月份的数据没有从表返回,则在12个月的另一个新array()中添加该月的0值,否则从表中找到的值。

Value | dname      | Total            
5     | Root Canal | 1         
8     | Root Canal | 1     

my code in php 我在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'];

This is what i get 这就是我得到的

  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 ) 

)

this is what i need 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 ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 1 [6] => 0 [7] => 0 [8] => 1 [9] => 0 [10] => 0 [11] => 0 [12] => 0 ) 

)

If I'm understanding your question correct then 如果我理解您的问题正确的话

$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;
}

Basically the code checks if there is already an array exists for a particular disease. 基本上,代码检查特定疾病是否已经存在阵列。 If not it creates an array of size 13 [to ignore 0] padded with value 0 and updates the value on the go. 如果不是,它将创建一个大小为13 [忽略0]的数组,并填充值0并在运行中更新该值。 Here disease becomes a key of outer array. 在这里,疾病成为外部阵列的关键。 You can use an map to disease name to integer ID if you wish to. 如果愿意,可以使用将疾病名称映射为整数ID的方法。 In that case 在这种情况下

$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'];
}

Edit: Since you seem to want to get all the diseases, it may be easier to do the whole thing as one query, like so: 编辑:由于您似乎想得到所有疾病,因此将整个事情作为一个查询来做可能会更容易,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM