我是PHP的新手,并且想要做一个foreach循环,如果之前输出了相同的项目,则不会重复结果。
这是我的代码:
foreach ( $attachments as $id => $attachment ) {
echo ($attachment->post_title);
}
正如您所看到的,这个词会被echo ($attachment->post_title);
拉出来。
有没有办法做一些检查并避免重复?
非常感谢你的帮助。
答案 0 :(得分:2)
$outputted = array();
foreach($attachments as $id => $attachment) {
if (!isset($outputted[$attachment->post_title])) {
echo $attachment->post_title;
$outputted[$attachment->post_title] = true;
}
}
答案 1 :(得分:2)
您可以像Rajesh建议的那样使用array_unique,而不必担心制作额外的阵列。
foreach ( array_unique($attachments) as $id => $attachment ) {
echo ($attachment->post_title);
}
答案 2 :(得分:0)
foreach ( $attachments as $id => $attachment ) {
if (!isset($outputs[$attachment->post_title])){
$outputs[$attachment->post_title] = true;
echo ($attachment->post_title);
}
}
答案 3 :(得分:0)
$output = array();
foreach ( $attachments as $id => $attachment ) {
if (!isset($output[$attachment->post_title])){
echo ($attachment->post_title);
$output[$attachment->post_title] = true;
}
}
答案 4 :(得分:0)
使用关联数组:
$used = array();
foreach ($attachments as $id => $attachment) {
if (!array_key_exists($attachment->post_title, $used)) {
$used[$attachment->post_title] = 1;
echo $attachment->post_title;
}
}
答案 5 :(得分:0)
也许是这样的?
foreach ( $attachments as $id => $attachment ) {
$attachments_posted[] = $attachment;
if (!array_search($attachment, $attachments_posted))
echo ($attachment->post_title);
}
答案 6 :(得分:0)
使用数组来跟踪您已经看过的标题:
$seen = array();
foreach ($attachments as $id => $attachment) {
if (array_key_exists($attachment->post_title, $seen)) {
continue;
}
$seen[$attachment->post_title] = true;
echo $attachment->post_title;
}