I’m generating a dummy array where keys are timestamps and values are zeroes. Start is today (date without time part) and going back for $days days in the past:
$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
This array is going to be merged with another one extracted from a MySQL result set (and its values should override dummy ones):
$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
Since array_merge operates a key reordering (when keys of integer type) i switched to + array operator, and the resulting array is reordered: new keys come first:
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
So question is + operator put those keys first and how can i solve this without using sort functions, as below:
$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
That’s because
+(applied to the arrays) appends the data from the right array that is not exists in the left array.You’ve used
var_dump($reals + $dummy);which means: take$realswhich consists of 1 item (today as the first and the only element) and append everything from$dummythat has another keys.The possible solutions are:
foreach