Advertisement
Guest User

Untitled

a guest
Jun 25th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. <?php
  2. ###################
  3. #### USAGE ####
  4. ###################
  5. $multidimensional_array = [[1,2, [6]], [5], 'hasan', null, -20, 4];
  6. $flattened_array = array();
  7.  
  8. echo "<pre>";
  9.  
  10. echo "<br>Flattened array using global variable:<br>";
  11. flatten_array($multidimensional_array);
  12. print_r($flattened_array);
  13.  
  14. echo "<br>Flattened array by reference:<br>";
  15. $flattened_array_using_reference = flatten_array_by_reference($multidimensional_array);
  16. print_r($flattened_array_using_reference);
  17.  
  18. echo "</pre>";
  19.  
  20.  
  21. ###################
  22. #### METHODS ####
  23. ###################
  24.  
  25. function flatten_array($array) {
  26. # Method to flatten a multidimensional array to one dimension.
  27. # Using a global variable
  28. #
  29. # $array = an array to convert into one dimension
  30.  
  31. if(is_array($array)){
  32. foreach($array as $item) {
  33. if(is_array($item)) {
  34. flatten_array($item);
  35. } else {
  36. $GLOBALS['flattened_array'][] = $item;
  37. }
  38. }
  39. }
  40. }
  41.  
  42. function flatten_array_by_reference($array, &$out = array()) {
  43. # Method to flatten a multidimensional array to one dimension.
  44. # using, array passing by reference
  45. #
  46. # $array - an array to convert into one dimension
  47. # $out - internal used argument for recursion
  48.  
  49. foreach($array as $key => $child){
  50. if(is_array($child))
  51. $out = flatten_array_by_reference($child, $out);
  52. else
  53. $out[] = $child;
  54. }
  55. return $out;
  56. }
  57. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement