<?php
/**
* Data Dataset Value Replacement Utility.
*
* Replaces values in a dataset with specified replacements.
* Handles various data types (numeric, string, boolean, null).
*
* @param array $data The dataset (array of arrays/values).
* @param array $replacements An associative array of replacements.
* Keys are the values to be replaced, values are the replacements.
* @return array The modified dataset.
*/
function replaceDatasetValues(array $data, array $replacements): array
{
$modifiedData = []; // Initialize an empty array to store the modified data.
foreach ($data as $row) { // Iterate through each row in the dataset.
$modifiedRow = []; // Initialize an empty array for the modified row.
foreach ($row as $value) { // Iterate through each value in the row.
if (isset($replacements[$value])) { // Check if the value exists in the replacements array.
$modifiedRow[] = $replacements[$value]; // Replace the value with the corresponding replacement.
} else {
$modifiedRow[] = $value; // Keep the original value if no replacement is found.
}
}
$modifiedData[] = $modifiedRow; // Add the modified row to the modified dataset.
}
return $modifiedData; // Return the modified dataset.
}
/**
* Example Usage
*/
// Sample Dataset
$data = [
[1, 'apple', true, null],
[2, 'banana', false, 1],
[3, 'apple', true, 'orange'],
];
// Replacements
$replacements = [
1 => 'one',
'apple' => 'apricot',
true => 'yes',
null => 'empty',
'orange' => 'grape'
];
// Apply replacements
$modifiedData = replaceDatasetValues($data, $replacements);
// Output (for demonstration)
echo "<pre>";
print_r($modifiedData);
echo "</pre>";
?>
Add your comment