|
| 1 | +<?php |
| 2 | + |
| 3 | + namespace CzProject; |
| 4 | + |
| 5 | + |
| 6 | + class Arrays |
| 7 | + { |
| 8 | + /** |
| 9 | + * @param array|\Traversable |
| 10 | + * @return array |
| 11 | + */ |
| 12 | + public static function flatten($arr) |
| 13 | + { |
| 14 | + $res = array(); |
| 15 | + |
| 16 | + static::recursiveWalk($arr, function ($val, $key) use (&$res) { |
| 17 | + if (is_scalar($val)) { |
| 18 | + $res[] = $val; |
| 19 | + } |
| 20 | + }); |
| 21 | + |
| 22 | + return $res; |
| 23 | + } |
| 24 | + |
| 25 | + |
| 26 | + /** |
| 27 | + * @param array|\Traversable |
| 28 | + * @return void |
| 29 | + */ |
| 30 | + public static function recursiveWalk($arr, $callback) |
| 31 | + { |
| 32 | + foreach ($arr as $key => $value) { |
| 33 | + if (is_array($value) || $value instanceof \Traversable) { |
| 34 | + static::recursiveWalk($value, $callback); |
| 35 | + |
| 36 | + } else { |
| 37 | + call_user_func_array($callback, array($value, $key)); |
| 38 | + // $callback($value, $key); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + /** |
| 45 | + * @param array|object[] |
| 46 | + * @param string|callback |
| 47 | + * @param string|callback |
| 48 | + * @return array |
| 49 | + */ |
| 50 | + public static function fetchPairs($data, $key, $value) |
| 51 | + { |
| 52 | + $list = array(); |
| 53 | + |
| 54 | + foreach ($data as $row) { |
| 55 | + $itemKey = NULL; |
| 56 | + $itemLabel = NULL; |
| 57 | + |
| 58 | + if (is_callable($key)) { |
| 59 | + $itemKey = call_user_func_array($key, array($row)); |
| 60 | + |
| 61 | + } else { |
| 62 | + $itemKey = is_array($row) ? $row[$key] : $row->{$key}; |
| 63 | + } |
| 64 | + |
| 65 | + if (is_callable($value)) { |
| 66 | + $itemLabel = call_user_func_array($value, array($row)); |
| 67 | + |
| 68 | + } else { |
| 69 | + $itemLabel = is_array($row) ? $row[$value] : $row->{$value}; |
| 70 | + } |
| 71 | + |
| 72 | + $list[$itemKey] = $itemLabel; |
| 73 | + } |
| 74 | + |
| 75 | + return $list; |
| 76 | + } |
| 77 | + |
| 78 | + |
| 79 | + /** |
| 80 | + * Merges arrays. Left has higher priority than right one. |
| 81 | + * @param array|NULL |
| 82 | + * @param array|NULL |
| 83 | + * @return array|string |
| 84 | + * @see https://github.com/nette/di/blob/master/src/DI/Config/Helpers.php |
| 85 | + */ |
| 86 | + public static function merge($left, $right) |
| 87 | + { |
| 88 | + if (is_array($left) && is_array($right)) { |
| 89 | + foreach ($left as $key => $val) { |
| 90 | + if (is_int($key)) { |
| 91 | + $right[] = $val; |
| 92 | + |
| 93 | + } else { |
| 94 | + if (isset($right[$key])) { |
| 95 | + $val = static::merge($val, $right[$key]); |
| 96 | + } |
| 97 | + $right[$key] = $val; |
| 98 | + } |
| 99 | + } |
| 100 | + return $right; |
| 101 | + |
| 102 | + } elseif ($left === NULL && is_array($right)) { |
| 103 | + return $right; |
| 104 | + |
| 105 | + } else { |
| 106 | + return $left; |
| 107 | + } |
| 108 | + } |
| 109 | + } |
0 commit comments