Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add keyBy() method to Arr helpers #41029

Merged
merged 6 commits into from
Feb 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'));
}
}