Example:
$obj1 = new stdClass();
$obj1->name = 'a';
$obj1->description = '1';
$obj2 = new stdClass();
$obj2->name = 'b';
$obj2->description = '2';
$obj3 = new stdClass();
$obj3->name = 'b';
$obj3->description = '3';
$array = array($obj1, $obj2, $obj3);
$grouped = Arrays::groupBy($array, Functions::extractField('name'));
Result:
Array
(
[a] => Array
(
[0] => stdClass Object
(
[name] => a
[description] => 1
)
)
[b] => Array
(
[0] => stdClass Object
(
[name] => b
[description] => 2
)
[1] => stdClass Object
(
[name] => b
[description] => 3
)
)
)
public function getClosedByRoundForCricket() { $hits = Hit::join('game_user->user')->where(['game_user_id' => $this->id])->order('hits.id asc')->fetchAll(); $byRound = Arrays::groupBy($hits, Functions::extract()->round); $closedInRound = []; $closed = [15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 25 => 0]; foreach ($byRound as $round => $hits) { $closedInCurrentRound = 0; foreach ($hits as $hit) { if (isset($closed[$hit->field])) { $closedField = min($hit->multiplier, 3 - $closed[$hit->field]); $closedInCurrentRound += $closedField; $closed[$hit->field] += $closedField; } } $closedInRound[$round] = $closedInCurrentRound; } return $closedInRound; }
public function groupBy($selector) { $this->_array = Arrays::groupBy($this->_array, $selector); return $this; }
private function _loadRelationObjectsIndexedById($localKeys) { $relationObject = $this->_relation->getRelationModelObject(); $relationObjects = $relationObject::where(array($this->_relation->getForeignKey() => $localKeys))->where($this->_relation->getCondition())->order($this->_relation->getOrder())->fetchAll(); return Arrays::groupBy($relationObjects, Functions::extractField($this->_relation->getForeignKey())); }
/** * @test */ public function shouldGroupByAndSort() { //given $product1 = new Product(array('name' => 'a', 'description' => '1', 'id_category' => '1')); $product2 = new Product(array('name' => 'b', 'description' => '2', 'id_category' => '2')); $product3 = new Product(array('name' => 'c', 'description' => '2', 'id_category' => '1')); $array = array($product1, $product2, $product3); //when $grouped = Arrays::groupBy($array, Functions::extractField('description'), 'id_category'); //then $this->assertEquals(array('1' => array($product1), '2' => array($product3, $product2)), $grouped); }