我正在生成一个虚拟数组,其中键是时间戳,值是零。开始是今天(没有时间部分的日期)并返回$days
过去几天:
$days = 10;
$limit = strtotime(date('Y-m-d'));
$start = $limit - (($days - 1) * 86400);
// Dummy array of timestamps and zeroes
$dummy = array_combine(range($start, $limit, 86400), array_fill(0, $days, 0));
var_dump($dummy);
array (size=10)
1337551200 => int 0
1337637600 => int 0
1337724000 => int 0
1337810400 => int 0
1337896800 => int 0
1337983200 => int 0
1338069600 => int 0
1338156000 => int 0
1338242400 => int 0
1338328800 => int 0 // Today is the last
这个数组将与另一个从 MySQL 结果集中提取的数组合并(并且它的值应该覆盖虚拟值):
$keys = array_map(function($e) { return strtotime($e['date']); }, $values);
$vals = array_map(function($e) { return intval($e['count']); }, $values);
// Array of real values coming from database
$reals = array_combine($keys, $vals);
var_dump($reals);
array (size=1)
1338328800 => int 2 // Today
由于array_merge
操作键重新排序(当键integer
类型时)我切换到+
数组运算符,并且结果数组被重新排序:新键首先出现:
var_dump($reals + $dummy);
array (size=10)
1338328800 => int 2 // Today become the first
1337551200 => int 0
1337637600 => int 0
1337724000 => int 0
1337810400 => int 0
1337896800 => int 0
1337983200 => int 0
1338069600 => int 0
1338156000 => int 0
1338242400 => int 0
所以问题是+
操作员将这些键放在首位,我如何在不使用排序功能的情况下解决这个问题,如下所示:
$merged = $reals + $dummy;
ksort($merged);
var_dump($merged);
array (size=10)
1337551200 => int 0
1337637600 => int 0
1337724000 => int 0
1337810400 => int 0
1337896800 => int 0
1337983200 => int 0
1338069600 => int 0
1338156000 => int 0
1338242400 => int 0
1338328800 => int 2