1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: namespace Jyxo\Spl;
15:
16: /**
17: * Utilities for working with arrays.
18: *
19: * @category Jyxo
20: * @package Jyxo\Spl
21: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
22: * @license https://github.com/jyxo/php/blob/master/license.txt
23: * @author Jakub Tománek
24: */
25: class ArrayUtil
26: {
27: /**
28: * Creates an array containing item range. Similar to range() but with closures.
29: * Params $low and $high are inclusive. If $low > $high, resulting array will be in descending order.
30: *
31: * @param mixed $low Minimal value
32: * @param mixed $high Maximal value
33: * @param \Closure $step Closure which creates next value from current
34: * @param \Closure $compare comparing closure for detecting if we're at the end of the range (Optional)
35: * @return array
36: */
37: public static function range($low, $high, \Closure $step, \Closure $compare = null)
38: {
39: $data = array($low);
40: $stepDown = $low > $high;
41: $compare = $compare ?: function ($a, $b) use ($stepDown) {
42: return $stepDown ? $a > $b : $a < $b;
43: };
44:
45: $current = $low;
46: while ($compare($current, $high)) {
47: $data[] = $current = $step($current);
48: }
49: return $data;
50: }
51:
52: /**
53: * Creates an associative array from iterator which doesn't return proper keys.
54: * Keys are generated by applying callback $key to the current value.
55: * It is also possible to apply another callback directly to the value.
56: * Key callback is called BEFORE value callback.
57: *
58: * Example:
59: * <code>
60: * $data = \Jyxo\Spl\ArrayUtil::keymap($iterator, function(Object $object) {
61: * return $object->getId();
62: * });
63: * </code>
64: *
65: * @param \Traversable $traversable Iterator
66: * @param \Closure $key Closure for generating keys
67: * @param \Closure $value Closure for modifying data (Optional)
68: * @return array
69: */
70: public static function keymap(\Traversable $traversable, \Closure $key, \Closure $value = null)
71: {
72: $data = array();
73: foreach ($traversable as $item) {
74: $data[$key($item)] = $value ? $value($item) : $item;
75: }
76: return $data;
77: }
78: }
79: