PHP splits arrays into groups based on a single field value

I have an array containing arrays of names and other details, in alphabetical order. Each array includes the first letter associated with the name.

Array ( [0] => Array ( [0] => a [1] => Alanis Morissette ) [1] => Array ( [0] => a [1] => Alesha Dixon ) [2] => Array ( [0] => a [1] => Alexandra Burke ) [3] => Array ( [0] => b [1] => Britney Spears ) [4] => Array ( [0] => b [1] => Bryan Adams ) ) 

I would like to display them grouped by first first, for example:

  A
 -
 Alanis morissette
 Alesha dixon
 Alexandra Burke

 B
 -
 Britney spears
 Bryan adams

 etc ... 

Is it possible?

+4
source share
2 answers

You can easily group them, even if they are not sorted:

 $groups=array(); foreach ($names as $name) { $groups[$name[0]][] = $name[1]; } 

You do not even need to save the first file to group them:

 $names = array( 'Alanis Morissette', 'Alesha Dixon', 'Alexandra Burke', 'Britney Spears', 'Bryan Adams', ... ); $groups=array(); foreach ($names as $name) { $groups[$name[0]][] = $name; } 
+12
source

Since your array is already sorted, you can simply scroll and trace the last letter shown. When it changes, you know that you are on the next letter.

 $lastChar = ''; foreach($singers as $s) { if ($s[0] != $lastChar) echo "\n".$s[0]."\n - \n"; echo $s[1]."\n"; $lastChar = $s[0]; } 
+6
source

Source: https://habr.com/ru/post/1307091/


All Articles