douzui6173 2013-09-24 10:06
浏览 39
已采纳

如何在php循环中检测a-z字母? [关闭]

I want to detect starting letter of string A-Z

Currently I am displaying data using loop which displays data from a to z

Now I want to detect data starting with letter "a" in loop

Is that possible using PHP?

I want same this http://cdn.ihwy.net/ihwy-com/labs/demos/jquery-listnav.html using PHP

Actually I want to add "Clear" name class after printing "a" letter data and so on for every letter (b,c,d.....z)

  • 写回答

3条回答 默认 最新

  • dongqi6486 2013-09-24 10:16
    关注

    This should work if all of the categories are stored in an array

    //Define the first letter that you want to focus on
    $letter = 'b';
    
    //Store all items in an array
    $categories = array('Books', 'Marketing', 'TV', 'Radio', 'Computers');
    
    //Loop thru
    for($i=0;$i<count($categories);$i++)
    {
        //This might be case sensitive, so lower the items and get the first letter of it
        if(strtolower(substr($categories[$i], 0, 1)) == $letter)
        {
             echo $categories[$i].'<br />';
        }
    }
    

    OR, if you're storing all of them in MySQL

    //Connect to MySQL
    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    //Query the DB for all categories beginnng with a particular letter
    $query = "SELECT * FROM table WHERE category LIKE '".$letter."%'";
    $result = mysqli_query($link, $query);
    $count = mysqli_num_rows($result);
    $i = 0;
    
    while ($row = mysqli_fetch_assoc($result)) {
      $categories[$i] = $row['category'];
    
      $i++;
    }
    
    //Loop thru
    for($i=0;$i<$count;$i++)
    {
       echo $categories[$i].'<br />';
    }
    

    You produce the exact same effect that's shown on the link you provided, you'll need more than just PHP; you'll need JS too. But, that's another task.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改