bcosca/fatfree — pull request #616 by ikkez (2014-05-06 16:44:36+00:00)
Title: [Jig] reduce handlers and group feature

I've played around with Jig again and added a little group feature that was still missing here.

It goes like this:

```php
$books = new \DB\Jig\Mapper($f3->get('DB'),'books');
$res = $books->find(null,array('group'=>'year'));
```
Now it first filters the database (`null` in this example), then sort the result array for the grouped fields and drops all rows that have the same value as its ancestors. You can define a handler which is called on every matching row. You can use that to create own new fields to aggredate fields or add computed values.

Like this:

```php
$books->reduce('year',function($dest,$cur){
if (!isset($dest['count']))
$dest['count'] = 1;
else
$dest['count']++;
return $dest;
});
$res = $books->find(null,array('group'=>'year'));
```

This will add a new `count` fields to your rows, that tells you how many books was found by each grouped year. We can also add some aggregation to our handlers:

```php
$books->reduce('year',function($dest,$cur){
// $dest is the first/final row that will remain in your result
// $cur is null or a descendant row that will be dropped due to the group action
if (!isset($dest['count']))
$dest['count'] = 1;
else
$dest['count']++;
// sum how many books we have in stock per released year
if (!isset($dest['sum_stock']))
$dest['sum_stock'] = 0;
else
$dest['sum_stock']+=$cur['stock'];
return $dest;
});
$res = $books->find(null,array('group'=>'year'));
```

You can also group on multiple fields and even sort the whole set afterwards using your own custom fields:
```php
$books->find(null,array('group'=>'year,author', 'order'=>'year SORT_ASC, sum_stock SORT_DESC'));
```

This was just a quick shot so far. Maybe another one can test this again if there is some spare time.