Lesson 1
Log Analysis and Timestamp Manipulation in PHP
Introduction

Welcome to our new coding practice lesson! We have an interesting problem in this unit that centers around data from a social networking app. The challenge involves processing logs from this app and extracting useful information from them. This task will leverage your skills in string manipulation, working with timestamps, and task subdivision. Let's get started!

Task Statement

Imagine a social networking application that allows users to form groups. Each group has a unique ID ranging from 1 to n, where n is the total number of groups. Interestingly, the app keeps track of when a group is created and deleted, logging all these actions in a string.

The task is to create a PHP function named analyzeLogs. This function will take as input a string of logs and output an array of strings representing the groups with the longest lifetime. Each string in the array contains two items separated by a space: the group ID and the group's lifetime. By "lifetime," we mean the duration from when the group was created until its deletion. If a group has been created and deleted multiple times, the lifetime is the total sum of those durations. If multiple groups have the same longest lifetime, the function should return all such groups in ascending order of their IDs.

For example, if we have a log string as follows: "1 create 09:00, 2 create 10:00, 1 delete 12:00, 3 create 13:00, 2 delete 15:00, 3 delete 16:00", the function will return: ["2 05:00"].

Solution Building: Step 1

First, we will split the input string into individual operations. In PHP, string manipulation can be handled using the explode() function.

php
1<?php 2function analyzeLogs($logs) { 3 $logList = explode(", ", $logs);
Solution Building: Step 2

Next, we delve deeper into the logs. For each logged group operation in the string, we need to parse its components. These include the group ID, the type of operation (create or delete), and the time of action.

php
1<?php 2function analyzeLogs($logs) { 3 $logList = explode(", ", $logs); 4 5 $timeDict = []; // Associative array to record the creation moment for each group in minutes 6 $lifeDict = []; // Associative array to record the lifetime for each group in minutes 7 8 foreach ($logList as $log) { 9 list($groupId, $action, $time) = explode(" ", $log); 10 $groupId = (int)$groupId;
Solution Building: Step 3

Now that we can identify the action performed on each group and when it's time to process these details. We convert the group ID into an integer and the timestamp into minutes from the start of the day. If the log entry marks a create action, we register the time of creation in an associative array under the group ID. If the entry signals delete, we calculate the lifetime of the group and store it in another associative array.

php
1<?php 2function analyzeLogs($logs) { 3 $logList = explode(", ", $logs); 4 5 $timeDict = []; // Associative array to record the creation moment for each group in minutes 6 $lifeDict = []; // Associative array to record the lifetime for each group in minutes 7 8 foreach ($logList as $log) { 9 list($groupId, $action, $time) = explode(" ", $log); 10 $groupId = (int)$groupId; 11 12 // Parsing the time from HH:MM format 13 list($hour, $minute) = explode(":", $time); 14 $currentTime = $hour * 60 + $minute; // Time in minutes from start of day 15 16 if ($action == "create") { 17 $timeDict[$groupId] = $currentTime; // If the group is created, log the creation time. 18 } elseif (isset($timeDict[$groupId])) { 19 // If the group is deleted, calculate its entire lifetime and remove it from the records. 20 $creationTime = $timeDict[$groupId]; 21 $lifetime = $currentTime - $creationTime; 22 if (!isset($lifeDict[$groupId])) { 23 $lifeDict[$groupId] = 0; 24 } 25 $lifeDict[$groupId] += $lifetime; 26 unset($timeDict[$groupId]); 27 } 28 }
Solution Building: Step 4

After recording the lifetimes of all groups, we can compare them to determine which group or groups had the longest lifetime. Finally, we return the ID or IDs of that group or groups, sorted in ascending order, along with their lifetime.

php
1<?php 2function analyzeLogs($logs) { 3 $logList = explode(", ", $logs); 4 5 $timeDict = []; // Associative array to record the creation moment for each group in minutes 6 $lifeDict = []; // Associative array to record the lifetime for each group in minutes 7 8 foreach ($logList as $log) { 9 list($groupId, $action, $time) = explode(" ", $log); 10 $groupId = (int)$groupId; 11 12 list($hour, $minute) = explode(":", $time); 13 $currentTime = $hour * 60 + $minute; // Time in minutes from start of day 14 15 if ($action == "create") { 16 $timeDict[$groupId] = $currentTime; 17 } elseif (isset($timeDict[$groupId])) { 18 $creationTime = $timeDict[$groupId]; 19 $lifetime = $currentTime - $creationTime; 20 if (!isset($lifeDict[$groupId])) { 21 $lifeDict[$groupId] = 0; 22 } 23 $lifeDict[$groupId] += $lifetime; 24 unset($timeDict[$groupId]); 25 } 26 } 27 28 // Find the longest lifetime 29 $maxLife = max($lifeDict); 30 31 // Building the result array where each item is a string of "group ID lifetime" if it has the longest lifetime. 32 $result = []; 33 foreach ($lifeDict as $groupId => $lifetime) { 34 if ($lifetime == $maxLife) { 35 $hours = floor($lifetime / 60); 36 $minutes = $lifetime % 60; 37 $timeString = sprintf("%02d:%02d", $hours, $minutes); 38 $result[] = $groupId . " " . $timeString; 39 } 40 } 41 42 // Sorting the result in ascending order of the group IDs 43 usort($result, function($a, $b) { 44 return (int)explode(" ", $a)[0] - (int)explode(" ", $b)[0]; 45 }); 46 47 return $result; 48} 49 50// Example Usage 51$logs = "1 create 09:00, 2 create 10:00, 1 delete 12:00, 3 create 13:00, 2 delete 15:00, 3 delete 16:00"; 52$result = analyzeLogs($logs); 53foreach ($result as $entry) { 54 list($groupId, $lifetime) = explode(" ", $entry); 55 echo "Group $groupId lifetime: $lifetime\n"; 56 // Outputs: Group 2 lifetime: 05:00 57}
Lesson Summary

Congratulations! You have successfully tackled a log analysis problem using PHP and worked with timestamped data, a real-world data type. Using PHP's string functions like explode(), formatting capabilities such as sprintf(), and array functions to manage data, you transformed raw strings into meaningful information. Real-life coding often involves understanding, dissecting, and analyzing data accurately, and this lesson has provided you with practical experience in using PHP to do just that. Now, you're ready to apply these new skills to more practice challenges!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.