Guest User

Untitled

a guest
Mar 23rd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. <?php
  2.  
  3. // Brief:
  4. // Write some code, that will flatten an array of arbitrarily
  5. // nested arrays of integers into a flat array of integers.
  6. // e.g. [[1,2,[3]],4] -> [1,2,3,4].
  7.  
  8. // This code requires at least PHP 5.4.0 to run.
  9.  
  10. // Test input.
  11. $input = [[13,77],[1,2,[3,5,[8,6]]],4];
  12. // $input = [2];
  13. // $input = [1,2];
  14. // Non-array input should cause an exception to be thrown.
  15. // $input = 4;
  16.  
  17. $output = [];
  18.  
  19. flatten_array($input, $output);
  20.  
  21. // json_encode() just so the output looks nice.
  22. echo "\n INPUT: " . json_encode($input) . "\n";
  23. echo "\n OUTPUT: " . json_encode($output) . "\n\n";
  24.  
  25. /**
  26. * Recursively traverse an array, adding non-array values to a second array.
  27. *
  28. * @param array $input
  29. * A multi-dimensional array of values to flatten.
  30. * @param array $output
  31. * An array used to store the found values.
  32. * Passed by reference so its state can be maintained.
  33. *
  34. * @return array
  35. * The input array as a flat array.
  36. */
  37. function flatten_array(array $input, array &$output) {
  38. foreach ($input as $value) {
  39. if (is_array($value)) {
  40. $output += flatten_array($value, $output);
  41. }
  42. else {
  43. $output[] = $value;
  44. }
  45. }
  46. return $output;
  47. }
Add Comment
Please, Sign In to add comment