我有一个项目数组,我正试图为它们生成一个按字母顺序排列的导航。
A|B|C|D|E|F|G|H等…
- 苹果
- 杏
- 胡萝卜
- Camel
- 狗
所以我想列出字母表中的每个字母,但只链接数组中有匹配项的字母。
到目前为止,我有:
$productArr = array('Apple','Apricot','Carrot','Camel','Dog');
$previous = null;
foreach(range('A','Z') as $alpha) {
$arrayCount = count($productArr);
for ($i=0; $i < $arrayCount; $i++) {
$firstLetter = $productArr[$i];
if ($firstLetter[0] == $alpha && $firstLetter[0] != $previous){
echo '<li><a href="#'.$alpha.'">'.$alpha.'</a></li>';
$previous = $alpha;
}elseif ($firstLetter[0] != $alpha && $alpha != $previous){
echo '<li>'.$alpha.'</li>';
$previous = $alpha;
}
}
}
直到elseif,它都能正常工作,如果您注释掉alseif,它会按预期打印链接列表。只需要弄清楚如何打印字母表的其余部分。
对于我哪里出了问题,我们将不胜感激。
干杯
我认为秘诀是将elseif移出内部循环。
<?php
$productArr = array('Apple','Apricot','Carrot','Camel','Dog', 'Rabbbit');
$previous = null;
foreach(range('A','Z') as $alpha) {
$arrayCount = count($productArr);
$printed = false;
for ($i=0; $i < $arrayCount; $i++) {
$firstLetter = $productArr[$i];
if ($firstLetter[0] == $alpha && $firstLetter[0] != $previous){
echo '<li><a href="#'.$alpha.'">'.$alpha.'</a></li>';
$previous = $alpha;
$printed = true;
}
}
if($printed == false){
echo '<li>'.$alpha.'</li>';
}
}
?>
您需要一个额外的步骤来首先对产品进行分组。
$productArr = array('Apple','Apricot','Carrot','Camel','Dog');
//This is the extra step
$productArrGroup = array();
foreach($productArr as $product){
if(!isset($productArrGroup[$product[0]])){
$productArrGroup[$product[0]] = array();
}
$productArrGroup[$product[0]][] = $product;
}
//You can even print the number of matching product for each $alpha like this !
foreach(range('A','Z') as $alpha) {
if(array_key_exists($alpha, $productArrGroup)){
echo '<li><a href="#'.$alpha.'">'.$alpha.' ('.count($productArrGroup[$alpha]).')</a></li>'."'n";
}else{
echo '<li>'.$alpha.'</li>'."'n";
}
}
上述代码的结果
<li><a href="#A">A(2)</a></li>
<li>B</li>
<li><a href="#C">C(2)</a></li>
<li><a href="#D">D(1)</a></li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
<li>I</li>
<li>J</li>
<li>K</li>
<li>L</li>
<li>M</li>
<li>N</li>
<li>O</li>
<li>P</li>
<li>Q</li>
<li>R</li>
<li>S</li>
<li>T</li>
<li>U</li>
<li>V</li>
<li>W</li>
<li>X</li>
<li>Y</li>
<li>Z</li>
注意:您可能希望不区分大小写地匹配字母,在这种情况下,您可以使用strtoupper
函数来$product[0]
请检查这可能是有用的
<?php
// define indexed array
$animals = array("wolf", "lion", "tiger", "iguana", "bear","zebra", "leopard");
// sort alphabetically by value
// result: ("bear", "iguana", "leopard", "lion", "tiger", "wolf","zebra")
sort($animals);
print_r($animals);
?>
这个:
$previous = null;
foreach($array as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter) echo "'n".$firstLetter."'n---'n'n";
$previous = $firstLetter;
echo $value."'n";
}
您的elseif
应该是||
而不是&&
elseif ($firstLetter[0] == $alpha && $alpha != $previous){
演示http://phpfiddle.org/main/code/i2q-97d