简体   繁体   English

从MySQL查询返回空结果时,在数组上分配零值

[英]Assign a zero value on an array when an empty result has been returned from a MySQL Query

Can I assign "0" value on an array that returned no results from a MySQL Query? 我可以在没有返回MySQL查询结果的数组上分配“ 0”值吗?

If so, can you show me how? 如果是这样,您能告诉我如何?

my code goes something like this: 我的代码是这样的:

    $grapes_query = mysql_query("SELECT fruitDate, fruitName, COUNT(*) FROM tbl_fruits WHERE fruitName='Grapes' GROUP BY 

    fruitDate");
    while ($grapes = mysql_fetch_assoc($grapes_query)){
    $grapes_array[]=$grapes['COUNT(*)'];

}

What if in a day, no grapes were found, can I assign "0" to its array value? 如果一天没有找到葡萄,该如何为它的数组值分配“ 0”呢?

Let's say 1/1/2012 = 3 grapes were counted, 1/2/2012 = no grapes were counted, 1/3/2012 = 5 grapes were counted..so the array should be like this. 假设1/1/2012 =计数了3个葡萄,1/2/2012 =未计数了葡萄,1/3/2012 =计数了5个葡萄..所以数组应该像这样

$grapes_array[0]=3;
$grapes_array[1]= <-- i want to assign a string or number here when a MySQL query is empty.
$grapes_array[2]=3;

i'm getting errors if no value was found. 如果找不到值,我会报错。

UPDATE: 更新:

在此处输入图片说明

fruit names should be grapes...:( 水果的名字应该是葡萄... :(

UPDATE 2: 更新2:

HERE is my sample database being used. 这里是我使用的示例数据库。

在此处输入图片说明

Here is the result I'm getting on your updated query 这是我在更新查询中得到的结果

在此处输入图片说明

The updated query will provide dates where there are fruit counts, but no Grapes counted on that day 更新后的查询将提供有水果计数但当天没有葡萄计数的日期

$grapes_query = mysql_query("SELECT f.fruitDate, IF(ISNULL(f1.count), 0, f1.count) as count FROM tbl_fruits f
    LEFT JOIN (SELECT fruitName, fruitDate, COUNT(*) as count from tbl_fruits d WHERE d.fruitName='Grapes' GROUP BY d.fruitDate) as f1 ON (f.fruitDate = f1.fruitDate) 
    GROUP BY f.fruitDate");
while ($grapes = mysql_fetch_assoc($grapes_query)){
   // use the fruitDate as a key for the array
   $grapes_array[$grapes['fruitDate']]= $grapes['count'];

}

You could do something like this: 您可以执行以下操作:

  • Select the minimum and maximum date from the table 从表格中选择最小和最大日期
  • Fill your output array with date => 0 pairs (initialize every date to zero) 用date => 0对填充输出数组(将每个日期初始化为零)
  • Run your script, but instead of creating a new numeric index with [] , use the date as a key 运行脚本,但不要使用[]创建新的数字索引,而应将日期用作键

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

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