array_merge_recursiveでPVの配列と平均滞在時間の配列同士を結合させて、tableで表示する。
<?php $date1 = date("Y-m-d", strtotime("-10 day")); $date2 = date("Y-m-d H:i:s"); $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $filter = [ 'date' => [ '$gte' => $date1, '$lte' => $date2] ]; $options = [ 'projection' => ['_id' => 0], 'sort' => ['_id' => -1], ]; $query = new MongoDB\Driver\Query($filter, $options); $cursor = $mng->executeQuery('app.na007', $query); foreach ($cursor as $document) { if(!is_null($document->referrer) and $document->referrer != ""){ $referrer = $document->referrer; $avgtime = $document->avgtime; $data[] = array($referrer=>$avgtime); } $page[] = $document->page; } // var_dump($data); function arraySum(array $arr) { $res = []; if (is_array($arr)) { foreach ($arr as $val) { foreach ($val as $k => $v) { if (isset($res[$k])) { $res[$k] = (double)($res[$k] + $v)/2; } else { $res[$k] = (double)$v; } } } } return $res; } $data = arraySum($data); // var_dump(arraySum($data)); $page = array_count_values($page); // var_dump($page); $newdata = (array_merge_recursive($page, $data)); arsort($newdata); print_r("<pre>"); var_dump($newdata); print_r("</pre>"); function s2h($avgtime){ $hours = floor($avgtime / 3600); $minutes = floor(($avgtime / 60)%60); $seconds = $avgtime % 60; $hms = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds); return $hms; } ?> <table> <th>Page</th><th>PageView</th><th>Avg time</th> <?php $i = 0; foreach($newdata as $key => $value){ if($i < 10 and !is_null($value[1])){ echo "<tr>"; echo "<td>".$key."</td><td>".$value[0]."</td><td>".s2h($value[1])."</td>"; echo "</tr>"; } else { echo "<tr>"; echo "<td>".$key."</td><td>".$value."</td><td>00:00:00</td>"; echo "</tr>"; } $i++; } ?> </table>
あ、ページごとのユニークなユーザー数もカウントしたくなってきた(笑)