ArrayHelper.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace fphammerle\helpers;
  3. class ArrayHelper
  4. {
  5. /**
  6. * @return array
  7. */
  8. public static function flatten(array $arr)
  9. {
  10. return iterator_to_array(
  11. new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr)),
  12. false
  13. );
  14. }
  15. /**
  16. * @param mixed $source_array
  17. * @param \Closure $callback
  18. * @return mixed
  19. */
  20. public static function map($source, \Closure $callback)
  21. {
  22. if(is_array($source)) {
  23. return array_map($callback, $source);
  24. } else {
  25. return $callback($source);
  26. }
  27. }
  28. /**
  29. * @param mixed $source_array
  30. * @param \Closure $callback
  31. * @return mixed
  32. */
  33. public static function mapIfSet($source, \Closure $callback)
  34. {
  35. if($source === null) {
  36. return null;
  37. } elseif(is_array($source)) {
  38. return array_map(
  39. function($v) use ($callback) {
  40. return $v === null ? null : $callback($v);
  41. },
  42. $source
  43. );
  44. } else {
  45. return $callback($source);
  46. }
  47. }
  48. /**
  49. * @param array $source_array
  50. * @param \Closure $callback
  51. * @return array
  52. */
  53. public static function multimap(array $source_array, \Closure $callback)
  54. {
  55. $mapped_array = [];
  56. foreach($source_array as $old_key => $old_value) {
  57. $pairs = $callback($old_key, $old_value);
  58. if($pairs === null) {
  59. // skipp
  60. } elseif(is_array($pairs)) {
  61. foreach($pairs as $new_key => $new_pair) {
  62. $mapped_array[$new_key] = $new_pair;
  63. }
  64. } else {
  65. throw new \UnexpectedValueException(
  66. sprintf('expected array, %s given', gettype($pairs))
  67. );
  68. }
  69. }
  70. return $mapped_array;
  71. }
  72. }