1. <?php
  2. /**
  3. * Indexes content of log entries for short-lived tasks.
  4. *
  5. * @param array $log_entries Array of log entries, each entry is an associative array.
  6. * Example: ['timestamp' => '2023-10-27 10:00:00', 'message' => 'Task started', 'data' => ['key1' => 'value1']]
  7. * @return array Associative array where keys are indexed terms and values are arrays of log entries containing that term.
  8. */
  9. function indexLogEntries(array $log_entries): array
  10. {
  11. $index = [];
  12. foreach ($log_entries as $entry) {
  13. // Iterate through all fields in each log entry
  14. foreach ($entry as $key => $value) {
  15. // Normalize the value to lowercase for consistent indexing
  16. $term = strtolower(trim($value));
  17. // If the term is not empty
  18. if (!empty($term)) {
  19. // If the term is not already a key in the index, create a new array for it
  20. if (!isset($index[$term])) {
  21. $index[$term] = [];
  22. }
  23. // Add the current log entry to the array associated with the term
  24. $index[$term][] = $entry;
  25. }
  26. }
  27. }
  28. return $index;
  29. }
  30. // Example usage:
  31. /*
  32. $log_entries = [
  33. ['timestamp' => '2023-10-27 10:00:00', 'message' => 'Task started', 'data' => ['key1' => 'value1']],
  34. ['timestamp' => '2023-10-27 10:00:05', 'message' => 'Processing data', 'data' => ['key2' => 'value2']],
  35. ['timestamp' => '2023-10-27 10:00:10', 'message' => 'Task completed', 'data' => ['key1' => 'value1']],
  36. ['timestamp' => '2023-10-27 10:00:15', 'message' => 'Error: Invalid data', 'data' => ['key3' => 'value3']]
  37. ];
  38. $index = indexLogEntries($log_entries);
  39. // Print the index (for demonstration)
  40. print_r($index);
  41. */
  42. ?>

Add your comment