我正在显示用CakePHP编写的应用程序的主题列表,如下所示:
<ul>
<?php foreach ($topics as $topic): ?>
<li>
<?php echo $topic['Topic']['title']; ?>
</li>
<?php endforeach; ?>
</ul>
我想做的就是显示它们:
<h3>A</h3>
<ul>
<li>animals</li>
<li>anger</li>
<li>age</li>
</ul>
<h3>B</h3>
<ul>
<li>bat</li>
<li>bird</li>
</ul>
etc...
我该怎么做?请记住,我也可以有数字,例如3D
ARRAY
array(
(int) 0 => array(
'Topic' => array(
'id' => '1',
'title' => 'awesome'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '1',
'topic_id' => '1',
'post_id' => '107'
)
)
),
(int) 1 => array(
'Topic' => array(
'id' => '2',
'title' => 'amazing'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '2',
'topic_id' => '2',
'post_id' => '107'
)
)
),
(int) 2 => array(
'Topic' => array(
'id' => '3',
'title' => 'jazz'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '3',
'topic_id' => '3',
'post_id' => '107'
)
)
)
)
答案 0 :(得分:0)
我的php有点生疏,所以我为可能的错误道歉,但逻辑很有希望清楚。你可以试试这个:
<?php
$lastTopic = ' ';
$first = true;
$close = false;
foreach ($topics as $topic):
$lastLetter = substr($lastTopic, 0, 1);
$thisLetter = substr($topic['Topic']['title'], 0, 1);
$isNewLetter = $lastLetter == $thisLetter;
if ($isNewLetter):
$close = true;
if($first) $first = false;
else echo "</ul>";
?>
<h3><?php echo $newLetter ?></h3>
<ul>
<?php endif; ?>
<li>
<?php
echo $topic['Topic']['title'];
$lastTopic = $topic['Topic']['title'];
?>
</li>
<?php endforeach; ?>
<?php if($close) echo "</ul>"; ?>
</ul>
基本思路是每次遇到以新字母开头的主题时,都会关闭html列表并创建一个新标题。这当然假定列表已经排序。
答案 1 :(得分:0)
您需要做的是首先创建一个排序项目数组,您可以foreach
通过。当您构建此数组时,请使用每个主题的第一个字母,并创建具有相同字母或数字的主题列表。
$topic
等于:$topic = array(
(int) 0 => array(
'Topic' => array(
'id' => '1',
'title' => 'awesome'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '1',
'topic_id' => '1',
'post_id' => '107'
)
)
),
(int) 1 => array(
'Topic' => array(
'id' => '2',
'title' => 'amazing'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '2',
'topic_id' => '2',
'post_id' => '107'
)
)
),
(int) 2 => array(
'Topic' => array(
'id' => '3',
'title' => 'jazz'
),
'TopicPost' => array(
(int) 0 => array(
'id' => '3',
'topic_id' => '3',
'post_id' => '107'
)
)
)
);
<?
foreach($topic as $currentTopic):
$thisLetter = strtoupper($currentTopic['Topic']['title'][0]);
$sorted[$thisLetter][] = $currentTopic['Topic']['title'];
unset($thisLetter);
endforeach;
foreach($sorted as $key=>$value):
echo '<h3>'.$key.'</h3>';
echo '<ul>';
foreach($value as $thisTopic):
echo '<li>'.$thisTopic.'</li>';
endforeach;
echo '</ul>';
endforeach;
?>
已成功测试。
答案 2 :(得分:-1)
试试这些代码:
<ul style="list-style-type:upper-alpha">
<?php foreach ($topics as $topic): ?>
<li>
<?php echo $topic['Topic']['title']; ?>
</li>
<?php endforeach; ?>
</ul>