ArrayHelper.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 array $source_array
  17. * @param \Closure $callback
  18. * @return array
  19. */
  20. public static function multimap(array $source_array, \Closure $callback)
  21. {
  22. $mapped_array = [];
  23. foreach($source_array as $old_key => $old_value) {
  24. $pairs = $callback($old_key, $old_value);
  25. if($pairs === null) {
  26. // skipp
  27. } elseif(is_array($pairs)) {
  28. foreach($pairs as $new_key => $new_pair) {
  29. $mapped_array[$new_key] = $new_pair;
  30. }
  31. } else {
  32. throw new \UnexpectedValueException(
  33. sprintf('expected array, %s given', gettype($pairs))
  34. );
  35. }
  36. }
  37. return $mapped_array;
  38. }
  39. }