1. <?php
  2. /**
  3. * Data Dataset Value Replacement Utility.
  4. *
  5. * Replaces values in a dataset with specified replacements.
  6. * Handles various data types (numeric, string, boolean, null).
  7. *
  8. * @param array $data The dataset (array of arrays/values).
  9. * @param array $replacements An associative array of replacements.
  10. * Keys are the values to be replaced, values are the replacements.
  11. * @return array The modified dataset.
  12. */
  13. function replaceDatasetValues(array $data, array $replacements): array
  14. {
  15. $modifiedData = []; // Initialize an empty array to store the modified data.
  16. foreach ($data as $row) { // Iterate through each row in the dataset.
  17. $modifiedRow = []; // Initialize an empty array for the modified row.
  18. foreach ($row as $value) { // Iterate through each value in the row.
  19. if (isset($replacements[$value])) { // Check if the value exists in the replacements array.
  20. $modifiedRow[] = $replacements[$value]; // Replace the value with the corresponding replacement.
  21. } else {
  22. $modifiedRow[] = $value; // Keep the original value if no replacement is found.
  23. }
  24. }
  25. $modifiedData[] = $modifiedRow; // Add the modified row to the modified dataset.
  26. }
  27. return $modifiedData; // Return the modified dataset.
  28. }
  29. /**
  30. * Example Usage
  31. */
  32. // Sample Dataset
  33. $data = [
  34. [1, 'apple', true, null],
  35. [2, 'banana', false, 1],
  36. [3, 'apple', true, 'orange'],
  37. ];
  38. // Replacements
  39. $replacements = [
  40. 1 => 'one',
  41. 'apple' => 'apricot',
  42. true => 'yes',
  43. null => 'empty',
  44. 'orange' => 'grape'
  45. ];
  46. // Apply replacements
  47. $modifiedData = replaceDatasetValues($data, $replacements);
  48. // Output (for demonstration)
  49. echo "<pre>";
  50. print_r($modifiedData);
  51. echo "</pre>";
  52. ?>

Add your comment