-
Notifications
You must be signed in to change notification settings - Fork 166
Arrays and Iterators
Dmitriy Zayceff edited this page Apr 29, 2015
·
10 revisions
JPHP has two useful class for working with arrays and iterators. The our way is universal methods that 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 the all methods working 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, support 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. Also, 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)->appand($array2)->appand(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 an generator
// The next code will throws an exception
foreach ($collection ... ) { }JPHP Group 2015