我有一个包含的父数组
年
1994,
1995,
1996,
1997,
1998,
1999,
2000,
2005
另一方面,我从我的db返回年份和计数的结果,现在,我想要做的是根据父数组(年)填充的数组,为类似的东西生成结果以下内容:
Results being Generated by sql +----------------+ YEAR | Count 1994 | 16 1995 | 16 1996 | 16 +----------------+
如果sql查询结果包含父数组年份的结果,则数组应按检查存储以下值
1994 | 16 1995 | 16 1996 | 16 1997 | 0 1998 | 0 1999 | 0 2000 | 0 2005 | 0
谢谢, 注意我希望如上所述在数组中生成reuslt,因为我必须将这些值传递给highcharts(用于生成图形)
答案 0 :(得分:2)
取决于$years_db
的构建方式,例如:
$years = array(1994, 1995, 1996, 1997, 1998, 1999, 2000, 2005);
$years_db = array(1994 => 16, 1995 => 16, 1996 => 16);
$array_temp = array();
foreach ($years as $year)
{
/* if (in_array($year, array_keys($years_db)))
* $array_temp[$year] = $years_db[$year];
* else
* $array_temp[$year] = 0;
*/
// @gumbo suggestion is more efficient. THX!
$array_temp[$year] = isset($years_db[$year]) ? $years_db[$year] : 0;
}
output of $array_temp:
array (
1994 => 16,
1995 => 16,
1996 => 16,
1997 => 0,
1998 => 0,
1999 => 0,
2000 => 0,
2005 => 0,
)