Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4. * Demonstration of how to flatten an array of arbitrarily nested arrays.
  5. * No error checking is done here. This assumes that the test array ($myarray) is properly formed.
  6. */
  7.  
  8. echo 'hello<br>';
  9.  
  10. // Some test data
  11. $myarray = array( 1,
  12. 2,
  13. 3.4,
  14. 4,
  15. 'mikey',
  16. array( 4,
  17. 5,
  18. array( 99,
  19. 88)
  20. ),
  21. 6
  22. );
  23.  
  24. // Something to hold the results
  25. $result = Array();
  26.  
  27. // let's get started
  28. echo 'Initial array:<br>';
  29. print_r($myarray);
  30.  
  31. flatten($myarray, $result);
  32.  
  33. echo '<br><br>Result array:<br>';
  34. print_r($result);
  35.  
  36.  
  37. /*
  38. * Flattens an array of arbitrarily-nested arrays.
  39. * While the instruction stated integer-only values would be used, this function flattens arrays regardless of their content.
  40. *
  41. * Parameters:
  42. * $input - the value to be checked/flattened
  43. * $result - passed by reference, a place to hold the results.
  44. */
  45.  
  46. function flatten($input, &$result) {
  47.  
  48. if(gettype($input) == 'array')
  49. {
  50. // if the input is an array, continue to flatten
  51. foreach($input as $key=>$value){
  52. flatten($value, $result);
  53. }
  54. } else {
  55. // Assign value to result array
  56. $result[] = $input;
  57. }
  58. // nothing to return
  59. }
  60. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement