2016-11-10 184 views
0

我有一个脚本,它以数组的形式从MongoDB获取数据并显示结果。该数组有很多记录。该取样阵列是如下:php数组foreach循环数据操作

array(2) { ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478199995) ["duration"]=> int(5) } 

array(2) { ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478203338) ["duration"]=> int(3) } 

array(2) { ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478201111) ["duration"]=> int(7) } 

array(2) { ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478206709) ["duration"]=> int(7) } 

array(2) { ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478202821) ["duration"]=> int(6) } 

array(2) { ["mac"]=> string(17) "2c:33:7a:10:f8:39" int(1478202366) ["duration"]=> int(4) } 

array(2) { ["mac"]=> string(17) "38:0b:40:ad:03:53" int(1478205023) ["duration"]=> int(2) } 

我显示像在上述阵列的MAC地址相对于MAC地址记录 “图2c:33:7A:10:F8:39” 有三个记录和“38:0B: 40:广告:03:53" 有四个,所以我会添加持续时间每个记录,并显示在浏览器这样

2c:33:7a:10:f8:39   16sec 
38:0b:40:ad:03:53   18sec 

我通过以下逻辑这样做,我认为是5000至6000的记录速度太慢。

我首先得到一个数组中的MAC地址并删除重复,然后在该数组上运行for循环,并为特定的mac添加所有持续时间,我的代码如下所示。

<?php 
foreach ($cursor as $document) { 
array_push($arr,$document["mac"]); 
} 
$arr=array_unique($arr); 
$duration=0; 

for($i=0;$i<count($arr);$i++){ 

foreach ($cursor as $document) { 

if($document["mac"]==$arr[$i]) 
{ 

$duration+=$document['assoc_time']; 

} 

echo $arr[$i]."  ".$duration; 
    } 

?> 

我如何使这个过程更快,以及如何在只有一个foreach循环中执行此任务。

+0

您可能希望查看[代码评论](http://codereview.stackexchange.com/)以了解如何使代码更好。作为开始,您可以通过在开始循环前存储该值来避免在每次迭代中计算'$ arr'的'count()':'$ arrayCount = count($ arr);' – Henders

回答