Skip to content

Commit

Permalink
[9.x] Add keyBy() method to Arr helpers (#41029)
Browse files Browse the repository at this point in the history
* Add index() method to Arr helpers

* fix data value

* fix spaces

* fix styleci

* change method name index to keyBy

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
medeirosinacio and taylorotwell authored Feb 15, 2022
1 parent ef7f80a commit 4b478a6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,18 @@ public static function isList($array)
return ! self::isAssoc($array);
}

/**
* Key an associative array by a field or using a callback.
*
* @param array $array
* @param callable|array|string
* @return array
*/
public static function keyBy($array, $keyBy)
{
return Collection::make($array)->keyBy($keyBy)->all();
}

/**
* Get a subset of the items from the given array.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1021,4 +1021,19 @@ function ($a, $b) {
['name' => 'John', 'age' => 8, 'meta' => ['key' => 3]],
], $sortedWithCallable);
}

public function testKeyBy()
{
$array = [
['id' => '123', 'data' => 'abc'],
['id' => '345', 'data' => 'def'],
['id' => '498', 'data' => 'hgi'],
];

$this->assertEquals([
'123' => ['id' => '123', 'data' => 'abc'],
'345' => ['id' => '345', 'data' => 'def'],
'498' => ['id' => '498', 'data' => 'hgi'],
], Arr::keyBy($array, 'id'));
}
}

0 comments on commit 4b478a6

Please sign in to comment.