Skip to content

Commit 4b478a6

Browse files
[9.x] Add keyBy() method to Arr helpers (#41029)
* 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>
1 parent ef7f80a commit 4b478a6

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,18 @@ public static function isList($array)
423423
return ! self::isAssoc($array);
424424
}
425425

426+
/**
427+
* Key an associative array by a field or using a callback.
428+
*
429+
* @param array $array
430+
* @param callable|array|string
431+
* @return array
432+
*/
433+
public static function keyBy($array, $keyBy)
434+
{
435+
return Collection::make($array)->keyBy($keyBy)->all();
436+
}
437+
426438
/**
427439
* Get a subset of the items from the given array.
428440
*

tests/Support/SupportArrTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1021,4 +1021,19 @@ function ($a, $b) {
10211021
['name' => 'John', 'age' => 8, 'meta' => ['key' => 3]],
10221022
], $sortedWithCallable);
10231023
}
1024+
1025+
public function testKeyBy()
1026+
{
1027+
$array = [
1028+
['id' => '123', 'data' => 'abc'],
1029+
['id' => '345', 'data' => 'def'],
1030+
['id' => '498', 'data' => 'hgi'],
1031+
];
1032+
1033+
$this->assertEquals([
1034+
'123' => ['id' => '123', 'data' => 'abc'],
1035+
'345' => ['id' => '345', 'data' => 'def'],
1036+
'498' => ['id' => '498', 'data' => 'hgi'],
1037+
], Arr::keyBy($array, 'id'));
1038+
}
10241039
}

0 commit comments

Comments
 (0)