PHP splitting arrays into groups based on one field's value

前端 未结 2 1427
不知归路
不知归路 2021-01-03 02:01

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
(
          


        
相关标签:
2条回答
  • 2021-01-03 02:41

    You can group them easily, even if they aren't sorted:

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

    You don't even need to store the first initial 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;
    }
    
    0 讨论(0)
  • 2021-01-03 02:51

    Since your array is already sorted, you could just loop through and track the last letter shown. When it changes, you know you're 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];
    } 
    
    0 讨论(0)
提交回复
热议问题