2013-07-29 48 views
0

我按字母順序排列了一個列表和數據庫mysql的數據。要讀取我使用foreach循環的數據。現在,我想要當第一個字母(a-> b- > c)將改變一個分隔符將被添加在'A'字符列表之後等等。試圖添加按字母順序排序的列表文字第一個字母將會改變

代碼:

$result = mysqli_query($con,"SELECT * FROM pages order by name ASC"); 
foreach($result as $val){ 
    echo $val['name']."<br>"; echo "<hr></hr>"; 
} 

在此先感謝

+0

我的代碼是:$結果= mysqli_query($ CON, 「SELECT * FROM頁按名稱排序ASC」); foreach($ result as $ val){ echo $ val ['name']。「
」; echo「


」; } – nitzkaushik

+2

編輯問題以包含您的代碼。 – Utkanos

回答

1
<?php 
$first = ''; 
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC"); 
foreach($result as $val){ 

    $first = substr($val['name'], 0, 1); 

    if ($first != $prev){ 
     echo '<h1>'.$first.'</h1>'; 
    } 

    echo $val['name']."<br>"; 

    $prev = $first; 
} 
1

試試這個:

$result = mysqli_query($con,"SELECT * FROM pages order by name ASC"); 

$lastChar = "?"; //initialization 

foreach($result as $val){ 
    if($lastChar != $val['name'][0]){  
    echo $val['name'][0].'<BR>';  //separator 
    } 
    echo $val['name']."<br>"; echo "<hr></hr>"; 
    $lastChar = $val['name'][0];   //update 
} 
0
$char = 'a'; 
foreach($result as $val) { 
    $newChar = substr($val['name'],0,1); 
    if ($newChar != $char) { 
    $char = $newChar; 
    echo "seperator for new character"; 
    } 
    //do your other stuff 
} 

這是你想要做什麼?

1

試試這個(未測試的代碼):

$firstLetter = 'A'; 
foreach($result as $val) { 
    $ch = substr($val['name'],1,1); 
    if($ch != $firstLetter) { 
    echo "<hr>"; 
    $firstLetter = $ch; 
    } 
    echo $val['name']."<br>"; 
} 
+0

這將檢索第二個字母,而不是第一個。 – 472084