$combined = collection($entities)->combine('id', function ($row) { return
$row}, 'group');
The function in the second argument will return the same row without
extracting any property from it. This is also equivalent to doing:
$combined = collection($entities)->indexBy('id')->groupBy('group');
On Saturday, May 9, 2015 at 4:33:54 PM UTC+2, Aday Talavera wrote:
>
> In CakePHP 2 I usually used Hash::combine to provide me some useful
> grouping of the DB data.
> Let me show you an example:
>
> Original array:
>
> <?php $data_rows = $this->find('all', $query); ?>
>
> // Output
> array(
> (int) 0 => array(
> 'DataRow' => array(
> 'id' => '70',
> 'section_id' => '2',
> 'group' => 'extrahotelero',
> 'date' => '2014-01-01',
> 'value' => '93150'
> )
> ),
> (int) 1 => array(
> 'DataRow' => array(
> 'id' => '202',
> 'section_id' => '5',
> 'group' => 'hotelero',
> 'date' => '2014-01-01',
> 'value' => '91.83'
> )
> ),
> ### more results ###
> )
>
>
> Use combine to group results in a fancy way:
>
> <?php $data_rows = Hash::combine($data_rows, '{n}.DataRow.id',
> '{n}.DataRow', '{n}.DataRow.group'); ?>
>
>
> //Output
> array(
> 'extrahotelero' => array(
> (int) 70 => array(
> 'id' => '70',
> 'section_id' => '2',
> 'group' => 'extrahotelero',
> 'date' => '2014-01-01',
> 'value' => '93150'
> ),
> (int) 97 => array(
> 'id' => '97',
> 'section_id' => '5',
> 'group' => 'extrahotelero',
> 'date' => '2014-01-01',
> 'value' => '48.91'
> ),
> ### more results ###
> ),
> 'hotelero' => array(
> (int) 202 => array(
> 'id' => '202',
> 'section_id' => '5',
> 'group' => 'hotelero',
> 'date' => '2014-01-01',
> 'value' => '91.83'
> ),
> (int) 193 => array(
> 'id' => '193',
> 'section_id' => '4',
> 'group' => 'hotelero',
> 'date' => '2014-01-01',
> 'value' => '7'
> ),
> ### more results ###
> )
>
>
> I tried the same with CakePHP3 without success using Collection:combine
> (as part of transformation after a query) and even tried mapReduce() (the
> result was near the expected, but I don't know how to get second level
> array keys.
> Collection:indexBy() and Collection:groupBy() helped.
>
> Maybe the problem is a limitation of the dot notation?
> Collection:combine('id', '{n}', 'group') didn't work.
>
--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
---
You received this message because you are subscribed to the Google Groups
"CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.