ArrayHelper.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 array $source_array
  30. * @param \Closure $callback
  31. * @return array
  32. */
  33. public static function multimap(array $source_array, \Closure $callback)
  34. {
  35. $mapped_array = [];
  36. foreach($source_array as $old_key => $old_value) {
  37. $pairs = $callback($old_key, $old_value);
  38. if($pairs === null) {
  39. // skipp
  40. } elseif(is_array($pairs)) {
  41. foreach($pairs as $new_key => $new_pair) {
  42. $mapped_array[$new_key] = $new_pair;
  43. }
  44. } else {
  45. throw new \UnexpectedValueException(
  46. sprintf('expected array, %s given', gettype($pairs))
  47. );
  48. }
  49. }
  50. return $mapped_array;
  51. }
  52. }