Group PHP results on first letter of name

后端 未结 6 1368
粉色の甜心
粉色の甜心 2020-12-10 17:25

I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the

相关标签:
6条回答
  • 2020-12-10 17:48

    In your view you could then loop the records and split them up:

    $current = '';
    foreach ($rows as $r) {
        if (!$current || strtolower($r['name'][0]) != $current) {
            $current = strtolower($r['name'][0]);
            echo strtoupper($current).'<br />---------------';
        }
        echo $row['name'].'<br />';
    }
    
    0 讨论(0)
  • 2020-12-10 17:51

    Allready tried something like this?

    $last = '';
    foreach($data as $key=>$row){
        if(substr($row['last_name'],0,1)!=$last) echo '<br /><br />'.substr($row['last_name'],0,1).'<br />----------------<br />';
        $last = substr($row['last_name'],0,1);
        echo $row['last_name'];
    }
    
    0 讨论(0)
  • 2020-12-10 17:52

    in your query, try adding something like:

    group by substr(last_name,1,1)
    

    i.e.

    select substr(last_name,1,1) as alpha, *
    from tableName
    group by substr(last_name,1,1)
    
    0 讨论(0)
  • 2020-12-10 17:59

    Yes you can achive this using MySql itself

    In my case brand_name going to be list out as you expected.

    Example :

    SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != ''  group by alpha
    UNION
    SELECT id, upper(SUBSTR(brand_name, 1, 1))  AS alpha FROM products WHERE  brand_name != '' order by brand_name COLLATE NOCASE
    

    Result :

        A
        A Card
        A Cef
        A Cef O
        B
        Bacticef Tab
        Bacticin
        Bactidrox
        Bactidrox Kid
        ........
    

    Hope it will help someone.

    0 讨论(0)
  • 2020-12-10 18:02

    Order the results by lastname on MySQL side and track the change of the first letter on PHP side:

    <?php
    
    $rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");
    
    while ($rec = mysql_fetch_assoc($rs)) {
        if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
            $initial = strtoupper(substr($rec['lastname'], 0, 1));
            print "$initial\n";
        }
        print $rec['lastname'] . "\n";
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-10 18:08
    $letter = null;
    foreach ($array as $word) {
      if ($letter != $word[0]) {
        $letter = $word[0];
        echo '<b>'.strtoupper($word[0]) . '</b><br/>';
      }
      echo strtoupper($word) . '<br/>';
    }
    

    and to tour query add line :

    order by `your_field` asc
    
    0 讨论(0)
提交回复
热议问题