我试图通过获取结果的第一个字符来制作一个按字母顺序排列的词汇表,并从中生成一个标题然后返回其下的结果的完整标题。我遇到的问题是,当我的函数调用1 - Z的结果时,A - Z的所有内容都会重复,而1 - 9的结果只显示一次。
这是我创建的功能。
function business_listings($states){
$dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");
$cityname = '';
$cityname = '<nav id="alphabetize">';
foreach (range('a', 'z') as $char) {
$cityname .= '<a href="#sort-'.$char.'">'.ucfirst($char).'</a>';
}
$cityname = '</nav>';
$curr_letter = '';
$cityname = '<div class="alpha_wrapper">';
foreach ($dbquery as $dbrow) {
$title_array = explode(' ', $dbrow->CityName);
$this_letter = substr($title_array[0], 0, 1);
//Here is where the problem starts to occur
if ($this_letter != $curr_letter) {
if (!empty($curr_letter)) {
$cityname .= '<div class="clear"></div></div><div class="alpha_wrapper">';
}
$curr_letter .= $this_letter;
$cityname .= '<div id="sort-'.strtolower($this_letter).'" class="alpha_title">';
$cityname .= $this_letter;
$cityname .= '</div>';
}//end of if statement where problem is
$cityname .='<div class="cityname">';
$cityname .= l($dbrow->CityName, $base_url.$_SERVER['REQUEST_URI'].'/'.strtolower(urlencode($dbrow->CityName)));
$cityname .= '</div>';
}
return $cityname;
}
例如循环就是这样的。
<div headerdiv>1</div>
10 palms
100 palms
1000 palms
<div headerdiv>2</div>
20 palms
200 palms
2000 palms
<div headerdiv>a</div>
apple 1
<div headerdiv>a</div>
apple 2
<div headerdiv>a</div>
apple 3
<div headerdiv>a</div>
apple 4
这一直持续到Z. 标题div应该只给出一个结果,苹果1 2 3和4应该在它之下。
如果我的例子不具有描述性,我还附上了截图。
有人有任何建议吗?
由于
答案 0 :(得分:2)
如果您将$this_letter
连接到$curr_letter
,则$curr_letter
的连续值将为1
,12
,12A
,{{1 },12AB
等等。因此,12ABC
将在$this_letter != $curr_letter
循环的每次迭代中评估为true
。代码中负责此类不良行为的行是:
foreach
您应该将该行更改为:
$curr_letter .= $this_letter; // concatenate