I have a script which get data from MongoDB in the form of array and show the result. The array has a number of records in the thousands. A sample array is as follows:
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) }
I am showing record with respect mac address like in above array MAC address "2c:33:7a:10:f8:39"
has three records and "38:0b:40:ad:03:53"
has four, so I will add duration of each record and show on browser like this
2c:33:7a:10:f8:39 16sec
38:0b:40:ad:03:53 18sec
I am doing this by following logic which I think is too slow for 5000 to 6000 records.
I first get the MAC address in an array and remove duplication and then run a for loop on that array and add all duration for specific MAC my code is as below.
<?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;
}
?>
How I can make this process fast and how to perform this task in only one foreach
loop.