Laravel 5 Collections: Reducing a Collection Into a Collection of Key/Array-Value Pairs With mapToDictionary

3 min read

In computing, a dictionary is a data structure where there exists a relationship between a single key and a value, or a list multiple values; examples of these are associative arrays and maps (both of which are easily implemented with PHP arrays). The mapToDictionary method allows you take a collection of data and reduce it such that the final result is a collection of key/value pairs. The resulting value for each key may be a single value, or another collection of items. The behavior of the mapToDictionary method ensures that all key/value pairs contain an array as the value, even if the value contains one element.

The mapToDictionary method defines a single $callback parameter, the return value of the callback function should be an associative array describing the relationship of the dictionary's key and values.

The mapToDictionary method does not modify the original array; the method returns a new collection with the dictionary structure.

Signature

1public function mapToDictionary(
2 callable $callback
3);

Example Use

In the following example, we have a collection of student names and test scores:

1// Student test scores.
2$testScores = new Collection([
3 ['score' => 0.84, 'name' => 'Bob'],
4 ['score' => 0.95, 'name' => 'Alice'],
5 ['score' => 0.78, 'name' => 'Charlie'],
6 ['score' => 0.92, 'name' => 'Alice'],
7 ['score' => 0.98, 'name' => 'Bob'],
8]);

While we could sort the list of tests scores by the student name, it is still not the easiest to quickly view the test scores of one particular student; ideally, we would like to have one entry for each student with their associated test scores.

We can accomplish this using the mapToDictionary method like so:

1$scores = $testScores->mapToDictionary(function ($item, $key) {
2 return [$item['name'] => $item['score']];
3});

In the previous example, the callback function returned an associative array describing the relationship between the student names and their test scores. After we have invoked the mapToDictionary method, the $scores collection would contain three elements for each of the students; each student element would have an array value containing their test scores:

1Collection {
2 #items: array [
3 "Bob" => array [
4 0 => 0.84
5 1 => 0.98
6 ]
7 "Alice" => array [
8 0 => 0.95
9 1 => 0.92
10 ]
11 "Charlie" => array [
12 0 => 0.78
13 ]
14 ]
15}

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch