Cakephp php MySQL


Cakephp php MySQL

的观点中有一个有效的foreach循环:

<? 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显示所有类别,但我想在我的列表中只显示唯一的类别。您如何实现这一目标?

这取决于您希望如何实际实现此目的。如果您仅将$words数组用于唯一类别,则最好在从数据库中检索数据时删除重复项。所以像这样:-

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

或者,如果您需要完整的$words数组用于其他目的,您可以使用Hash::extract()从数组中提取类别,然后使用 PHP 的 array_unique 方法删除仅用于循环的重复项:

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