2015-06-11 19 views
0

我有一个工作foreach循环中我观点CakePHP的PHP MySQL的

<? foreach($words as $word): ?> 
     <td><?= $word['Word']['category'] ?></td> 
<? endforeach; ?> 

功能在我控制器

public function index() 
{ 
    $this->Paginator->settings = array(
    'conditions' => array('Word.role' => CakeSession::read("Auth.User.username")), 
    'limit' => 100 
); 
$data = $this->Paginator->paginate('Word'); 
$this->set('words', $data); 
} 

foreach显示所有类别,但我想说明在我的列表中只有唯一的类别。你如何做到这一点?

+0

您可以在查询中使用['GROUP BY'(https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html)或发现的情况下, cakePHP –

回答

1

这取决于你想如何实现这个目标。如果您仅将$words阵列用于独特类别,那么在从数据库检索数据时最好删除重复项。因此,像这样: -

$words = $this->Word->find('all', ['group' => 'category']); 

另外,如果您需要完整的$words阵列用于其他目的,你可以使用Hash::extract()然后用PHP's array_unique方法来删除重复的只是你的循环数组提取类: -

$categories = Hash::extract($words, '{n}.Word.category'); 
$uniqueCategories = array_unique($categories); 
foreach ($uniqueCategories as $category) { 
    echo '<td>' . $category . '</td>'; 
} 
+0

如果我用第一种方式 - 意外'[' – andrzej

+0

其次也不行 – andrzej

+0

我曾尝试把它放在C ontroller和index - view - nothing – andrzej