蛋糕php php MySQL
Cakephp php MySQL
我的 view 中有一个有效的 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()
and then use PHP's array_unique
方法从数组中提取类别,以便为您的循环删除重复项:-
$categories = Hash::extract($words, '{n}.Word.category');
$uniqueCategories = array_unique($categories);
foreach ($uniqueCategories as $category) {
echo '<td>' . $category . '</td>';
}
我的 view 中有一个有效的 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()
and then use PHP's array_unique
方法从数组中提取类别,以便为您的循环删除重复项:-
$categories = Hash::extract($words, '{n}.Word.category');
$uniqueCategories = array_unique($categories);
foreach ($uniqueCategories as $category) {
echo '<td>' . $category . '</td>';
}