2012-02-26 139 views
1

我想通过第一个字母从数据库表中获取和分组记录。因此,例如:基于第一个字母的CakePHP中的组记录?

一个
阿尔弗雷德


布赖恩

Ç
克里斯托弗

...

理想情况下,我想我的数据结构来列如下:

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> 
... 
+0

[第一个字母名称的PHP组结果]可能重复(http://stackoverflow.com/questions/6760222/group-php-results-on-first-letter-of-name) – 2012-02-27 05:24:05

回答

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> 

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

希望有帮助! (PS代码没有测试...但你明白了吧应该有任何错别字)

0

试试这个:

$peoplebyletter = array(); 

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

debug($peoplebyletter); 

未经测试。让我知道它是否有效。

相关问题