1. <?php
  2. /**
  3. * Function to add timestamp metadata to a given data item.
  4. *
  5. * @param mixed $data The data item to add metadata to. Can be anything.
  6. * @param string $key The key for the timestamp metadata (e.g., 'created_at', 'modified_at').
  7. * @return mixed The data item with the added timestamp metadata.
  8. */
  9. function addTimestampMetadata($data, $key = 'created_at') {
  10. // Get the current timestamp.
  11. $timestamp = time();
  12. // Add the timestamp metadata to the data item.
  13. if (is_array($data)) {
  14. $data[$key] = $timestamp;
  15. } else {
  16. $data = [$key => $timestamp]; // Wrap in array if not already
  17. }
  18. return $data;
  19. }
  20. /**
  21. * Function to update the timestamp metadata of a data item.
  22. *
  23. * @param mixed $data The data item to update.
  24. * @param string $key The key for the timestamp metadata.
  25. * @return mixed The data item with updated timestamp metadata.
  26. */
  27. function updateTimestampMetadata($data, $key = 'modified_at') {
  28. $timestamp = time();
  29. if (is_array($data)) {
  30. $data[$key] = $timestamp;
  31. } else {
  32. $data = [$key => $timestamp];
  33. }
  34. return $data;
  35. }
  36. // Example Usage:
  37. $my_data = "This is some data.";
  38. $data_with_timestamp = addTimestampMetadata($my_data, 'created_at');
  39. echo "Created at: " . $data_with_timestamp['created_at'] . "\n";
  40. $array_data = ['name' => 'Example', 'value' => 123];
  41. $array_data_with_timestamp = addTimestampMetadata($array_data, 'created_at');
  42. print_r($array_data_with_timestamp);
  43. $updated_data = updateTimestampMetadata($array_data_with_timestamp, 'modified_at');
  44. print_r($updated_data);
  45. ?>

Add your comment