1. <?php
  2. /**
  3. * Synchronizes resources of arrays for a local utility with limited memory usage.
  4. *
  5. * This function iterates through multiple arrays, synchronizing their elements
  6. * based on a provided key. It's designed for scenarios where loading entire
  7. * arrays into memory is undesirable, especially with large datasets.
  8. *
  9. * @param array $arrays An array of arrays to synchronize. Each inner array
  10. * should have a common key.
  11. * @param string $key The key to use for synchronizing the arrays.
  12. * @return array|null A new array containing the synchronized data. Returns null on error.
  13. */
  14. function syncArrays(array $arrays, string $key): ?array
  15. {
  16. if (empty($arrays)) {
  17. return []; // Return empty array if no input arrays
  18. }
  19. $synchronizedData = [];
  20. // Get the keys from the first array to use as the basis for synchronization
  21. $keys = array_keys($arrays[0]);
  22. foreach ($keys as $key_value) {
  23. $values = []; // Store values for a specific key
  24. // Iterate through all arrays to find values for the current key
  25. foreach ($arrays as $array) {
  26. if (isset($array[$key])) {
  27. $values[] = $array[$key];
  28. } else {
  29. $values[] = null; // Handle missing keys gracefully
  30. }
  31. }
  32. // Find the unique values for the current key
  33. $uniqueValues = array_values(array_unique($values));
  34. // Build the synchronized data for the current key
  35. foreach ($uniqueValues as $value) {
  36. $synchronizedData[$key_value] = $value;
  37. }
  38. }
  39. return $synchronizedData;
  40. }
  41. /**
  42. * Example usage (demonstrates memory efficiency)
  43. */
  44. // Simulate large arrays
  45. $array1 = [];
  46. for ($i = 0; $i < 1000; $i++) {
  47. $array1[$i] = 'value_' . $i;
  48. }
  49. $array2 = [];
  50. for ($i = 500; $i < 1500; $i++) {
  51. $array2[$i] = 'value_' . $i;
  52. }
  53. $array3 = [];
  54. for ($i = 1000; $i < 2000; $i++) {
  55. $array3[$i] = 'value_' . $i;
  56. }
  57. $arrays = [$array1, $array2, $array3];
  58. $synchronized = syncArrays($arrays, 'id');
  59. if ($synchronized !== null) {
  60. print_r($synchronized);
  61. } else {
  62. echo "Error during synchronization.\n";
  63. }
  64. ?>

Add your comment