如何在PHP中显示一次重复值


How to show once a repeated value in PHP

我有这个代码:

foreach($this->authors as $autor){
    if($autor->author == $filter_autor){
        echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
    }else{
        echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
      }
};

作者可能会被重复多次。我如何更改此代码,使其只打印重复显示的每一个代码?

提前感谢您的帮助。

$var = '';
foreach($this->authors as $autor){
    if($var != $autor->author)
    {
       if($autor->author == $filter_autor){
           echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
       }else{
           echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
        }
    }
    $var = $autor->author;
};

未测试,但请尝试以下操作:

foreach(array_unique($this->authors) as $autor){
    if($autor->author == $filter_autor){
        echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
    }else{
        echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
      }
};

最好的选择是在开始输出之前过滤数组。

如果这不可能,无论出于什么原因(包括个人偏好),都可以尝试这样的方法:

$used_authors = array();
foreach($this->authors as $autor){
  if(!isset($used_authors[$autor->author]){
    if($autor->author == $filter_autor){
        echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
    }else{
        echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
    }
    $used_authors[$autor->author] = true;
  }
};

希望这将帮助您

$newarray=array_unique($this->authors);
    foreach($newarray as $autor){
        if($autor->author == $filter_autor){
            echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
        }else{
            echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
          }
    }

了解array_unique()

希望这将帮助您

 $unieq_array=array_unique($this->authors);
        foreach($unieq_array as $autor){
            if($autor->author == $filter_autor){
                echo '<option value="'.$autor->author.'" selected="selected">'.$autor-     >author.'</option>';
            }else{
                echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
              }
        };