1. <?php
  2. /**
  3. * Function to nest JSON structures for an experiment.
  4. *
  5. * @param array $data The initial data array.
  6. * @param array $nesting_rules An array defining the nesting structure.
  7. * Each element should be an associative array with:
  8. * - 'key': The key to nest under.
  9. * - 'value': The value to assign to the nested structure.
  10. * - 'type': 'array' or 'object' (default: 'array')
  11. * @return array The nested JSON structure.
  12. */
  13. function nestJson(array $data, array $nesting_rules): array
  14. {
  15. $result = $data;
  16. foreach ($nesting_rules as $rule) {
  17. $key = $rule['key'];
  18. $value = $rule['value'];
  19. $type = $rule['type'] ?? 'array'; // Default to array if type not specified
  20. if (!is_array($result) || !isset($result[$key])) {
  21. $result[$key] = []; // Initialize if not present
  22. }
  23. if ($type === 'array') {
  24. $result[$key] = array_merge($result[$key], [$value]); // Append to existing array
  25. } elseif ($type === 'object') {
  26. $result[$key][$value] = $value; // Set key-value pairs in an object
  27. }
  28. }
  29. return $result;
  30. }
  31. // Example Usage:
  32. /*
  33. $initial_data = [
  34. 'experiment_id' => '123',
  35. 'timestamp' => '2024-10-27',
  36. 'sensor_readings' => [10, 20, 30]
  37. ];
  38. $nesting_rules = [
  39. ['key' => 'results', 'value' => ['temperature' => 25, 'humidity' => 60]],
  40. ['key' => 'metadata', 'value' => ['user' => 'testuser', 'version' => '1.0']],
  41. ['key' => 'processed_data', 'value' => [
  42. 'filtered' => true,
  43. 'smoothed' => false
  44. ]]
  45. ];
  46. $nested_data = nestJson($initial_data, $nesting_rules);
  47. print_r($nested_data);
  48. */
  49. ?>

Add your comment