November 18, 2016 —John Koster
This article will look at retrieving a unique list of languages using Laravel helper functions. The following student data will be used:
1<?php 2 3$students = [ 4 'student-001' => [ 5 'first_name' => 'John', 6 'languages' => [ 7 'count' => 2, 8 'names' => [ 9 'French',10 'English'11 ]12 ],13 'courses' => [14 'CIS 100',15 'CIS 200'16 ]17 ],18 'student-002' => [19 'first_name' => 'Jane',20 'languages' => [21 'count' => 2,22 'names' => [23 'Spanish',24 'English'25 ]26 ],27 'courses' => [28 'CIS 100',29 'CIS 200'30 ]31 ],32 'student-003' => [33 'first_name' => 'Jim',34 'courses' => [35 'HUMA 1302'36 ]37 ]38 ];
To quickly retrieve a list of all the unique languages all students speak, we can first flatten the array using the flatten
method:
1<?php2 3$languages = Arr::flatten($languages);
which would create the following array:
1array(4) {2 [0] "French"3 [1] "English"4 [2] "Spanish"5 [3] "English"6}
At this point PHP's array_unique
can be used:
1<?php2 3$languages = array_unique($languages);
which would return the following array:
1array(3) {2 [0] "French"3 [1] "English"4 [2] "Spanish"5}
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.