2013-09-24 47 views
0

我要檢測字符串的首字母AZ如何在php循環中檢測a-z字母?

目前我使用循環從一個顯示數據到z

現在我想檢測數據的開頭字母「一」中顯示數據循環

使用PHP有可能嗎?

我想這同樣使用http://cdn.ihwy.net/ihwy-com/labs/demos/jquery-listnav.html PHP

其實我想要打印的「A」字母數據等的每一個字母后加「清除」名稱類(B,C,d .....ž )

+0

你能否提供一些代碼? – Lance

+0

upvote從哪裏來?這個問題質量很低。 – ppeterka

回答

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。但是,這是另一項任務。

0

是有幾種方式,一個非常簡單的一種是隻檢查字符串中的第一個字母:

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

如果你想多一點看上你可以做同樣的使用preg_match

foreach($lines as $line) { 
    if(preg_match("/^a.*/", $line) { 
     echo $line 
    } 
} 
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);