-
Notifications
You must be signed in to change notification settings - Fork 160
Arrays and Iterators
Edgar Asatryan edited this page Dec 7, 2019
·
10 revisions
JPHP has two useful classes for working with arrays and iterators. Our way is universal methods which can work with arrays and iterators.
-
php\lib\Items
- an util class with static methods -
php\util\Flow
- flows are used for the lazy array/iterator operations to save the RAM memory.
The JPHP has own util class for working with iterators and arrays php\lib\Items
, for example:
Why Items?
We cannot use Array
because all methods work with not only arrays, List
because it's a lexer keyword, Arr
because it's an ugly reduction of the Array
word, Collection
- it's too long word.
use php\lib\Items;
$keys = Items::keys($array);
// instead of
$keys = array_keys($array);
-
sizeof, count
->Items::count
, supports iterators -
iterator_to_array, array_values
->Items::toArray
-
???
->Items::toList
,Items::toList([1, 2], 3, 4, [5]) -> [1, 2, 3, 4, 5]
-
???
->Items::flatten
-
usort, sort
->Items::sort
-
ksort
->Items::sortByKeys
-
array_push
->Items::push
-
array_pop
->Items::pop
-
array_shift
->Items::shift
-
array_unshift
->Items::unshift
Supports not only arrays, also iterators and traversable. Flow implements Iterator.
-
array_map
->Flow::of($array)->map()
-
array_filter
->Flow::of($array)->find()
,Flow::of($array)->findOne()
-
array_reduce
->Flow::of($array)->reduce()
-
array_merge
->Flow::of($array1)->append($array2)->append(array3)->toArray()
-
???, foreach
->Flow::of(...)->each()
,Flow::of(...)->eachSlice
-
array_keys
->Flow::of(...)->keys()
-
LimitIterator, array_filter
->Flow::of(...)->limit($n)
-
???, array_filter
->Flow::of(...)->skip($n)
-
asort, usort
->Flow::of(...)->sort()
-
ksort
->Flow::of(...)->sortByKeys()
-
array_values
->Flow::of(...)->toArray()
-
implode
->Flow::of(...)->toString()
Many methods of Flow return a new Flow instance, so you can use fluent interface to lazy manipulate arrays and iterators, for instance:
$someArray = [....];
$collection = Flow::of($someArray)
->filter(function($el) { return $el > 18; })
->map(function($el, $key) { return "[" . $el . "]"; });
foreach ($collection as $key => $value) {
var_dump($value);
}
// You can use a flow instance only one time as a generator
// The next code will throw an exception
foreach ($collection ... ) { }
JPHP Group 2015