如何在php循环中检测a-z字母?

时间:2013-09-24 10:06:14

标签: php sorting loops

我想检测字符串A-Z的起始字母

目前我正在使用循环显示数据,该循环显示来自 a到z

的数据

现在我想检测以字母“a”开头

开头的数据

使用PHP可以吗?

我希望使用PHP

这个http://cdn.ihwy.net/ihwy-com/labs/demos/jquery-listnav.html

实际上我想在打印“a”字母数据之后添加“清除”名称等等等等每个字母(b,c,d ...... z)

3 个答案:

答案 0 :(得分:1)

如果所有类别都存储在数组

中,这应该有效
//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 />';
    }
}

或者,如果您将所有这些内容存储在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 />';
}

您产生的效果与您提供的链接上显示的完全相同,您需要的不仅仅是PHP;你也需要JS。但是,这是另一项任务。

答案 1 :(得分:0)

是的,有几种方法,一个非常简单的方法就是检查字符串中的第一个字母:

foreach($lines as $line) {
    if($line[0] == "a") {
        echo $line
    }
}

如果你想更加喜欢,你可以使用preg_match来做同样的事情:

foreach($lines as $line) {
    if(preg_match("/^a.*/", $line) {
        echo $line
    }
}

答案 2 :(得分:0)

如果您使用的是MySQL之类的存储引擎,则应在结果之前对数据进行排序,例如:

SELECT * FROM table WHERE name LIKE 'a%'

如果您正在使用内存,则可能需要使用某种过滤功能:

$a = [];
foreach ($data as $i => $v)
    if ($v{0} == "a") $a[] $v;

// $a now contains everything on a*

对结果进行排序:

natsort($a);
相关问题