首页 文章

基于第一个字母的CakePHP中的组记录?

提问于
浏览
1

我想要通过第一个字母从数据库表中获取和分组记录 . 例如:

A Alfred B Brian C Christopher ......

理想情况下,我希望我的数据结构如下:

Array
(
    [A] => Array
    (
        [0] => Array
        (
            [Person] => Array
            (
                [id] => 12
                [name] => Alfred
            )
        )
    )
)

我可以使用原始的MySQL查询执行此操作,但不确定CakePHP是否支持此开箱即用 . 我只是想要分组记录,所以我可以迭代它们并为每个字母创建一个无序列表:

<h2>A</h2>
<ul>
  <li>Alfred</li>
</ul>
<h2>B</h2>
<ul>
  <li>Brian</li>
</ul>
<h2>C</h2>
<ul>
  <li>Christopher</li>
</ul>
...

2 回答

  • 0

    我要做的是:按名称排序,然后循环排序:

    $people = $this->Person->find('all', array(
        'order' => 'Person.name ASC'
    ));
    

    然后你可以这样做:

    $letter = '';
    foreach($people as $person) {
        $firstLetter = strtolower(substr($person['Person']['name'], 0, 1));
        if ($firstLetter !== $letter) {
            $letter = $firstLetter;
        }
        $_people[$letter][] = $person;
    }
    $people = $_people;
    

    或者直接在视图中执行此操作,因此您无需将其循环两次:

    <ul>
    <?php $letter = 'first'; ?>
    <?php foreach ($people as $person) : ?>
        <?php $firstLetter = strtolower(substr($person['Person']['name'], 0, 1)); ?>
        <?php if ($firstLetter !== $letter) : ?>
            <?php if ($letter !== 'first') : ?>
                </ul></li>
            <?php endif; ?>
            <?php $letter = $firstLetter; ?>
            <li><h2><?php echo $firstLetter; ?></h2><ul>
        <?php endif; ?>
        <li><?php echo $person['Person']['name']; ?></li>
    <?php endforeach; ?>
    </ul></li></ul>
    

    我不知道如何通过使用find调用来获得这个结构(除了进行26次调用或创建包含所有字母的db表),我不明白为什么这将是neccesairy .

    希望有所帮助! (ps代码没有经过测试......但是你明白了 . 如果有任何错别字)

  • 0

    试试这个:

    $peoplebyletter = array();
    
    foreach($people as $person){
        $peoplebyletter[strtolower(substr($person['Person']['name'], 0, 1))][] = $person;
    }
    
    debug($peoplebyletter);
    

    没有测试过 . 如果有效,请告诉我 .

相关问题