<?php
/**
* Function to nest JSON structures for an experiment.
*
* @param array $data The initial data array.
* @param array $nesting_rules An array defining the nesting structure.
* Each element should be an associative array with:
* - 'key': The key to nest under.
* - 'value': The value to assign to the nested structure.
* - 'type': 'array' or 'object' (default: 'array')
* @return array The nested JSON structure.
*/
function nestJson(array $data, array $nesting_rules): array
{
$result = $data;
foreach ($nesting_rules as $rule) {
$key = $rule['key'];
$value = $rule['value'];
$type = $rule['type'] ?? 'array'; // Default to array if type not specified
if (!is_array($result) || !isset($result[$key])) {
$result[$key] = []; // Initialize if not present
}
if ($type === 'array') {
$result[$key] = array_merge($result[$key], [$value]); // Append to existing array
} elseif ($type === 'object') {
$result[$key][$value] = $value; // Set key-value pairs in an object
}
}
return $result;
}
// Example Usage:
/*
$initial_data = [
'experiment_id' => '123',
'timestamp' => '2024-10-27',
'sensor_readings' => [10, 20, 30]
];
$nesting_rules = [
['key' => 'results', 'value' => ['temperature' => 25, 'humidity' => 60]],
['key' => 'metadata', 'value' => ['user' => 'testuser', 'version' => '1.0']],
['key' => 'processed_data', 'value' => [
'filtered' => true,
'smoothed' => false
]]
];
$nested_data = nestJson($initial_data, $nesting_rules);
print_r($nested_data);
*/
?>
Add your comment