[mysql]PHP 错误︰ 请注意︰ 未定义的索引︰ 在一月

标签: MySQL PHP
发布时间: 2017/1/9 22:04:27
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有张新闻张贴在月此代码︰

$months = array("January","February","March","April",
                "May","June","July","August","September","October",
                "November","December");
$mews = DB->fetch("SELECT id, YEAR(FROM_UNIXTIME(date)) AS YEAR, 
                          MONTHNAME(FROM_UNIXTIME(date)) AS MONTH, 
                          COUNT(id) AS TOTAL 
                   FROM article
                   WHERE YEAR(FROM_UNIXTIME(date)) = 2014
                   GROUP BY YEAR, MONTH ORDER BY YEAR, MONTH");

// Index article counts by month and year for easy lookup
$indexedNewsData = array();
foreach ($mews as $news) {
  $indexedNewsData[$news['MONTH']] = $news['TOTAL'];
}
// Then print output
foreach($mews AS $news){            

  foreach ($months as $month) {
    $total = intval($indexedNewsData[$month]);
    echo '<li>'.$month.' '.$total.'</li>';
  }     
}

但是,对于每月 0 后我看到此错误︰

Notice: Undefined index: January in......

我如何做可以狐狸此错误? !

演示︰ http://stackdemo.url.ph/test/

资料来源︰ http://stackdemo.url.ph/test/test

解决方法 1:

你应该正确初始化数组。

$indexedNewsData = array();
foreach($months as $month) $indexedNewsData[$month] = 0;

foreach($mews as $news)
   ...
赞助商