我在这里要做的基本上是从$stats
一个$counts
包含四个数组的数组开始,其中每个数组是一对:键是以毫秒为单位的时间戳,而值是计数。我在 Windows 7 x64 上使用 PHP 版本 5.3.14。
问题是:为什么我得到否定数组键值以及如何避免这种情况?见var_dump()
下文:
$stats = array();
$stats[] = array(
'subtype' => 'small_text_message_user',
'count' => '6',
'date' => '2012-06-03'
);
$stats[] = array(
'subtype' => 'small_text_message_auto',
'count' => '3',
'date' => '2012-07-03',
);
$stats = array(
'subtype' => 'newsletter_auto',
'count' => '11',
'date' => '2012-07-16',
);
$counts = array();
$counts['small_text_message_user'] = array();
$counts['small_text_message_auto'] = array();
$counts['newsletter_user'] = array();
$counts['newsletter_auto'] = array();
foreach($data as $stat) :
$millisecs = 1000 * strtotime($stat['date']);
$count = intval($stat['count']);
$counts[$stat['subtype']][$millisecs] = $count;
var_dump($millisecs, $count);
endforeach;
var_dump($counts);
结果是错误的:
float 1338674400000
int 6
float 1341266400000
int 3
float 1342389600000
int 11
array (size=4)
'small_text_message_user' =>
array (size=1)
-1355396352 => int 6
'small_text_message_auto' =>
array (size=1)
1236603648 => int 3
'newsletter_user' =>
array (size=0)
empty
'newsletter_auto' =>
array (size=1)
-1935163648 => int 11
一个例子(实际上有效)是一小段代码,我在其中生成一个“虚拟”数组:
public function createTimestampRangeFromDates(\DateTime $from,
\DateTime $to = null)
{
$start = strtotime($from->format('Y-m-d 00:00:00'));
$limit = strtotime(sprintf('%s 00:00:00', $to ? $to->format('Y-m-d')
: date('Y-m-d') . ' 00:00:00'));
return range($start, $limit, 86400);
}
// Test
$start = new \DateTime('2012-06-27');
$end = new \DateTime('2012-07-07'); // 10 days
$timestamps = createTimestampRangeFromDates($start, $end);
$millisecs = array_combine($timestamps, array_fill(0, count($timestamps), 0));
var_dump($millisecs);
这工作正常,我得到大整数作为键:
array (size=11)
'1340748000000' => int 0
'1340834400000' => int 0
'1340920800000' => int 0
'1341007200000' => int 0
'1341093600000' => int 0
'1341180000000' => int 0
'1341266400000' => int 0
'1341352800000' => int 0
'1341439200000' => int 0
'1341525600000' => int 0
'1341612000000' => int 0
哦,如果这很重要,那么这段代码的目的是执行以下操作:
$values = array_merge($millisecs, $counts['newsletter_auto']);
那就是用真实值覆盖虚拟数组。
按照@hakre 的建议更新小测试用例
$result1 = array();
$result2 = array();
$test = array('2012-06-03', '2012-07-03', '2012-07-16');
foreach($test as $date) :
$result1[1000 * strtotime($date)] = 0;
$result2[] = 1000 * strtotime($date);
endforeach;
var_dump($result1); // Not working
var_dump($result2); // Works
结果显示 的否定键$result1
。问题仅在于键,而不是值(因为值转换为float
):
array (size=3)
-1355396352 => int 0
1236603648 => int 0
-1935163648 => int 0
array (size=3)
0 => float 1338674400000
1 => float 1341266400000
2 => float 1342389600000