|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Boudewijn Schoon <[email protected]> |
|
4
|
|
|
* @copyright Zicht Online <http://zicht.nl> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Zicht\Itertools\lib\Traits; |
|
8
|
|
|
|
|
9
|
|
|
use Zicht\Itertools as iter; |
|
10
|
|
|
|
|
11
|
|
|
trait GroupByTrait |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* Make an iterator that returns consecutive groups from this |
|
15
|
|
|
* iterable. Generally, this iterable needs to already be sorted on |
|
16
|
|
|
* the same key function. |
|
17
|
|
|
* |
|
18
|
|
|
* When $strategy is a string, the key is obtained through one of |
|
19
|
|
|
* the following: |
|
20
|
|
|
* 1. $value->{$strategy}, when $value is an object and |
|
21
|
|
|
* $strategy is an existing property, |
|
22
|
|
|
* 2. call $value->{$strategy}(), when $value is an object and |
|
23
|
|
|
* $strategy is an existing method, |
|
24
|
|
|
* 3. $value[$strategy], when $value is an array and $strategy |
|
25
|
|
|
* is an existing key, |
|
26
|
|
|
* 4. otherwise the key will default to null. |
|
27
|
|
|
* |
|
28
|
|
|
* Alternatively $strategy can be a closure. In this case the |
|
29
|
|
|
* $strategy closure is called with each value in this iterable and the |
|
30
|
|
|
* key will be its return value. $strategy is called with two |
|
31
|
|
|
* parameters: the value and the key of the iterable as the first and |
|
32
|
|
|
* second parameter, respectively. |
|
33
|
|
|
* |
|
34
|
|
|
* The operation of groupBy() is similar to the uniq filter in Unix. |
|
35
|
|
|
* It generates a break or new group every time the value of the key |
|
36
|
|
|
* function changes (which is why it is usually necessary to have |
|
37
|
|
|
* sorted the data using the same key function). That behavior |
|
38
|
|
|
* differs from SQL's GROUP BY which aggregates common elements |
|
39
|
|
|
* regardless of their input order. |
|
40
|
|
|
* |
|
41
|
|
|
* > $list = [['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two'], ['type'=>'B', 'title'=>'three']] |
|
42
|
|
|
* > iter\iterable($list)->groupBy('type') |
|
43
|
|
|
* 'A'=>[['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two']] 'B'=>[['type'=>'B', 'title'=>'three']] |
|
44
|
|
|
* |
|
45
|
|
|
* @param null|string|\Closure $strategy |
|
46
|
|
|
* @param bool $sort |
|
47
|
|
|
* @return iter\lib\GroupbyIterator |
|
48
|
|
|
*/ |
|
49
|
2 |
|
public function groupBy($strategy, $sort = true) |
|
50
|
|
|
{ |
|
51
|
2 |
|
return iter\groupBy($strategy, $this, $sort); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|