Skip to content

Commit

Permalink
Update PhpCollection.php
Browse files Browse the repository at this point in the history
  • Loading branch information
izica authored Oct 27, 2019
1 parent b19eff9 commit f82347c
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions PhpCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public function slice($offset, $length)
*/
public function limit($length)
{
$this->arCollection = array_slice($this->arCollection,0, $length);
$this->arCollection = array_slice($this->arCollection, 0, $length);
return $this;
}

Expand Down Expand Up @@ -242,12 +242,19 @@ public function map($function = false)
* @param $key
* @return PhpCollection
*/
public function keyBy($key)
public function keyBy($keyOrFunc)
{
$arData = [];
foreach ($this->arCollection as $arItem) {
$arData[$arItem[$key]] = $arItem;
if (is_callable($keyOrFunc)) {
foreach ($this->arCollection as $arItem) {
$arData[$keyOrFunc($arItem)] = $arItem;
}
} else {
foreach ($this->arCollection as $arItem) {
$arData[$arItem[$keyOrFunc]] = $arItem;
}
}

return new PhpCollection($arData);
}

Expand Down Expand Up @@ -487,4 +494,23 @@ public function unique()

return new PhpCollection($arResult);
}

/**
* @return number
*/
public function sum($sKey = null)
{
$nResult = 0;
if ($sKey === null) {
foreach ($this->arCollection as $nItem) {
$nResult += $nItem;
}
} else {
foreach ($this->arCollection as $arItem) {
$nResult += $arItem[$sKey];
}
}

return $nResult;
}
}

0 comments on commit f82347c

Please sign in to comment.