0
我有一些數據,我循環和使用if語句的字母化。我的代碼有效,但問題在於它看起來像是一個「很長的路」。我想知道是否還有另一種我錯過的方法可以使這更容易。使用數組/字母表化表數據使用數組/ if語句
這裏是我的PHP:
// MY QUERY
$query1 = "SELECT `categoryid`, `categoryname`
FROM `my_table_category`
ORDER BY `my_table_category`.`categoryname` ASC";
$browse = mysql_query($query1) or die(mysql_error());
$browse_rows = array();
while($row = mysql_fetch_assoc($browse)){
$browse_rows[] = $row;
}
// HERE MY ARRAYS FOR THE ALPHABET
$list_a = array(); $list_b = array(); $list_c = array();
$list_d = array(); $list_e = array(); $list_f = array();
$list_g = array(); $list_h = array(); $list_i = array();
// etc...
// HERE IS WHERE I'M GRABBING THE CATEGORY NAMES BY THEIR FIRST LETTER
// AND ADDING THEM TO AN ARRAY
foreach($browse_rows as $row){
if($row['categoryname'][0] == 'A'){
$list_a[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'B'){
$list_b[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'C'){
$list_c[] = $row['categoryname'];
}elseif($row['categoryname'][0] == 'D'){
$list_d[] = $row['categoryname'];
}
} //etc...
這裏是我的HTML:
<!-- HERE IS HOW I DISPLAY MY DATA -->
<div id="topics_a">
<h2>A</h2>
<ul class="browse_list">
<?
foreach($list_a as $name){
if ($holdcat <> $name) {
$holdcat = $name; ?>
<li><a href="index.php?state="<? echo $template->State."#".$browse_row['categoryid'];?>><? echo $name; ?></a></li>
<? }} ?>
</ul>
</div>
<div id="topics_b">
<h2>B</h2>
<ul class="browse_list">
<?
foreach($list_b as $name){
if ($holdcat <> $name) {
$holdcat = $name; ?>
<li><a href="index.php?state="<? echo $template->State."#".$browse_row2['categoryid'];?>><? echo $name; ?></a></li>
<? }} ?>
</ul>
</div>
//etc...
答案後更新:
//UPDATED PHP
foreach ($browse_rows as $row) {
$initial = $row['categoryname'][0];
$lists[$initial][] = $row['categoryname'];
}
//UPDATED HTML
<? foreach ($lists as $letter => $list){ ?>
<div>
<h2><? echo $letter; ?></h2>
<ul class="browse_list">
<?
$list = array_unique($list);
foreach ($list as $cat) {
?>
<li><a href="#"><? echo $cat; ?></a></li>
<? } ?>
</ul>
</div>
<? } ?>
爲什麼你需要每個字母的排列? –
codereview.stackexchange.com – shmosel
你只使用一個列表(例如'$ list_a')或全部26個? –