如果单个单词已经输出,继续


if single word already output, continue

我是PHP的新手,并且想做一个foreach循环,如果相同的项目之前已经输出,则不会重复结果。

下面是我的代码:

    foreach ( $attachments as $id => $attachment ) {
        echo ($attachment->post_title);
    }

如您所见,该单词将被echo ($attachment->post_title);拉出。

是否有一种方法可以做一些检查并避免重复?

非常感谢您的帮助

$outputted = array();
foreach($attachments as $id => $attachment) {
   if (!isset($outputted[$attachment->post_title])) {
      echo $attachment->post_title;
      $outputted[$attachment->post_title] = true;
   }
}

您可以像Rajesh建议的那样使用array_unique,而不必担心生成额外的数组。

foreach ( array_unique($attachments) as $id => $attachment ) {
        echo ($attachment->post_title);
}
foreach ( $attachments as $id => $attachment ) {
         if (!isset($outputs[$attachment->post_title])){
            $outputs[$attachment->post_title] = true;
            echo ($attachment->post_title);
         }
}

你可以这样做:

$output = array();
foreach ( $attachments as $id => $attachment ) {
    if (!isset($output[$attachment->post_title])){
        echo ($attachment->post_title);
        $output[$attachment->post_title] = true;
    }
}

使用关联数组

$used = array();
foreach ($attachments as $id => $attachment) {
    if (!array_key_exists($attachment->post_title, $used)) {
        $used[$attachment->post_title] = 1;
        echo $attachment->post_title;
    }
}

也许是这样的?

foreach ( $attachments as $id => $attachment ) {
    $attachments_posted[] = $attachment;
    if (!array_search($attachment, $attachments_posted))
        echo ($attachment->post_title);
}

使用一个数组来跟踪您已经看到的标题:

$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;
}