2012-02-26 19 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); 

未經測試。讓我知道它是否有效。

相關問題